[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Lua VM 'meta' questions
- From: "Jerome Vuarand" <jerome.vuarand@...>
- Date: Wed, 4 Oct 2006 14:02:46 -0400
* Can a LUA script call functions in another Lua script, i.e. will
the VM automatically load the Lua script in which the function is
referenced?
The Lua VM won't do that. However you can design a system that does
that. For example you can suppose that all globals are members of a
module. You can then override your global environment so that any access
to a module that don't exist will load (using require) the proper
module. Example (not tested):
setmetatable(_G, {
__index = function(t, k)
local module = require(k)
rawset(t, k, module)
return module
end;
})
-- Then any access to a global variable that don't already
-- exist will call require with the variable name:
mylib.foo()
-- ...is equivalent to...
_G["mylib"]["foo"]()
-- ...which becomes...
local module = require("mylib")
rawset(_G, "mylib", module)
module["foo"]()
-- Any subsequent access to the module won't trigger the
-- metamethod because the entry in _G already exists (thanks
-- to the rawset call)
* When compiling Lua scripts, will the compiler resolve function
calls to functions within other Lua scripts, i.e. will the compiler
ensure the function exists and that the parameters are correct?
Two answers for two questions.
Unresolved accesses to variables, which includes functions, at compile
time become accesses to the runtime environment thanks to the syntactic
sugar "a = 32" => "_G['a'] = 32". The function may or may not be present
at runtime, and you cannot check it at compilation time. Lua is a
dynamic language.
Concerning the parameters checks, there is no check of the parameters of
a function in Lua because any combination of declared parameters and
provided parameters is valid. Example (not tested but should be ok):
function f(arg1, arg2, arg3)
print(arg1, arg2, arg3)
end
f() --> nil nil nil
-- undefined arguments at call time have the value nil
function g()
print("Hello world!")
end
g("foo", f, 32) --> Hello world!
-- arguments are discared