Here's how you create new globals in Lua:
Code:
max@server:~$ lua
Lua 5.1.2 Copyright (C) 1994-2007 Lua.org, PUC-Rio
> _G["foo"] = "bar"
> print (foo)
bar
> varname = "spam"
> _G[varname] = "eggs"
> print (varname)
spam
> print (spam)
eggs
> print (_G["varname"])
spam
> print(_G[_G["varname"]])
eggs
>
_G is a special table that points to the global scope. I suppose the language is sort of "cheating" by doing it this way, but it works well.
You can also use the dot "." if you don't want to use strings as names, but this has its limits:
Code:
> print(_G.varname)
spam
> print(_G._G.varname) -- _G contains itself because _G is a global, so this doesn't quite work.
spam
> print(_G.(_G.varname)) -- This doesn't work either
stdin:1: '<name>' expected near '('
> print (_G[_G.varname]) --this does work
eggs
>
Also, heck, why not? Let me show you what some of this stuff is good for:
Code:
> _G["print"]("hello") -- functions are part of _G as well
hello
> _G["PRINT"]=function(str) print ( string.upper(str) ) end -- create a wrapper around "print"
> PRINT ("hello")
HELLO
> _G["_print"]=_G["print"]
> _G["print"] = function(str) _print (string.upper (str)) end -- completely replace "print"
> print "hi"
HI
>
Bookmarks