[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE:Need standard kernel supported class in Lua, was: Macros and expressivity
- From: Eike Decker <eike@...>
- Date: Mon, 14 Jan 2008 12:18:27 +0100
Zitat von "Grellier, Thierry" <t-grellier@ti.com>:
> (On a tangential note, it might be interesting to require special syntax
> for
> accessing the global environment -- e.g., global symbols would have to
> be
> prefixed with "$". Variables would be "local by default" except that you
> would still have to declare them so essentially they would be
> "undeclared by
> default".)
I think it would bloat the code with quite lot's of $ signs (imagine all the
global tables containing the functions you need everywhere - io, table, string
etc.).
However, something similar like what you suggest this could already be done by
assigning a nearly empty environment table to a function:
----
function f ()
local print = G.print
print(x) -- error is thrown here
end
local env = {G = _G}
setmetatable(env,{
__index = function(t,key)
error("accessing nonexisting variable named "..tostring(key),2)
end,
__newindex = function(t,key,val)
error("implicit variable declaration forbidden",2)
end}
)
setfenv(f,env)
f() -- throws error on line 3 which says that x does not exist
----
It's a bit inconvenient because the environment needs to be assigned to the
function before it works. However there could be an automatism using metatables
which will assign this special function environment automaticly or by calling a
function:
----
local env = {G = _G}
setmetatable(env,{
__index = function(t,key)
error("accessing nonexisting variable named "..tostring(key),2)
end,
__newindex = function(t,key,val)
error("implicit variable declaration forbidden",2)
end}
)
function safeenv (func)
return setfenv(func,env)
end
-- method 1:
foo = safeenv(function ()
-- uncomfortable somehow
end)
-- method 2:
safebox = {}
setmetatable(safebox, {
__newindex = function (t,k,func) rawset(t,k,setfenv(func,env)) end
})
function safebox.foo ()
-- all functions in safebox will be assigned
-- the env function environment
end
However, I would rather want to have an editor which knows the scope and would
color the typed names depending on their local/global type.
Or a lua compiler flag could make the compiler complain about accessing global
values without using the _G table.
Or do I overlook a case where the scope can only be determined during runtime?
Eike