Game Development Reference
In-Depth Information
print("Retrieving the variable :", name)
end
})
what(was, this)
Notice that we still get an error that the global variable
what
was not found. When we access a
member from the table, the member is returned, but if the member is not present, the
__index
function is used to calculate or determine the data to be returned. If there is no
__index
function,
then we get the error.
We can rectify that by using
rawset
and making sure that there is a global function (if it is not found)
function(tbl, name)
print("Retrieving the variable :", name)
rawset(tbl,name,{})
end
what
is declared. This fails because
what
is a table, not a function, and
we are trying to invoke it like a function.
An easy way to rectify this is to replace the
rawset(tbl, name,{})
with
rawset(tbl, name, function()
end
. This way, we return a function that can be called without invoking errors in Lua. The most important
point here is that the
__index
metamethod has to return something expected in the context.
setmetatable(_G, {__index =
function(tbl, name)
print("Name :", name)
rawset(tbl,name,function() end)
return rawget(tbl, name)
end
})
what(was, this)
This is fine; however, since
Vader
and
Luke
are also not defined, we cannot have them converted into
functions. One logical solution is to identify that all variable names starting with a lowercase letter
are functions and all uppercase names are variables. So, in the case of
father(Vader, Luke)
,
Vader
and
Luke
would be variables, while
father
would be a function.
setmetatable(_G, {__index =
function(tbl, name)
if name:match("^[A-Z]") then
rawset(tbl, name, {} )
else