| Andreas Rozek |
|
Lua_02 - replaces "intrinsic" functionsIn "Lua_02" some of intrinsic functions found by "Lua_01" will be replaced by user-defined ones. The concrete intention is to extend the built-in functions print and tostring in order to be able to handle tables. Additionally, the program introduces a new global function encodedString which replaces control (and other non-printable) characters within strings by their corresponding escape sequence - this prevents these characters from causing any undesired side-effects when sent to stdout. The program itself should not be too difficult to understand - the most difficult part might be the handling of tables and lists within function tostring: if the given argument represents a table itself containing a function named tostring or toString, that function takes on to convert the table into a string (due to the fact that the function receives the table/list as its first and only argument, the distinction between function and method is unimportant). Otherwise, by means of Lua's introspective capabilities, the table's contents will be written into the resulting string in table or list format - depending on its internal structure: lists will be encoded as a sequence of elements (in ascending order of its indices), tables as a sequence of key-value pairs. Table keys will be encoded directly, values (and this concerns list elements as well) by a recursive invocation of tostring. In order to avoid end-less loops, the nest level of these recursive calls is limited by the setting of toString_DefaultNestLevel (currently 4 levels). "Lua_02" should be invoked without any command line arguments lua Lua_02.lua and yields the following output: Lua_02 - replaces intrinsic functions with user-defined ones
PI = 3.141592653589793
_INPUT = (userdata)
_ALERT = (function)
Complex = {im=0,re=0}
Vector = {1,2,3}
Special = {["a non-symbolic key"]="a\nspecial\0\"value\"\127",innerTable={1,2,3}}
{} = {}
{n=0} = {}
It is recommended to analyze this output along with the source code - provided that you are familiar with Lua, you should not experience any surprises. Source CodeThe source code of this example is available for download:
As the functions defined within "Lua_02.lua" will also be used in other programming examples, they may be downloaded separately as a Lua script file:
References
|
| http://www.Andreas-Rozek.de/Lua/Acquainting/Lua_02_en.html | (last Modification: 15.04.2002) |