lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



RLake@oxfam.org.pe wrote:
There is no reason to do rawget(ReadOnly, name) since ReadOnly
has no metatable. (And if it did, it should probably be respected.)
ReadOnly[name] is considerably faster because it requires neither
a lookup in the environment table nor a function call.

Okay, good point. But I'm sure Jean Claude has translated this example to C and used either lua_rawget or lua_gettable, in which case there isn't much difference.

Note to newbies: if you don't use rawset in the __newindex handler, you will get a "C stack overflow" error.

There is a worse fault in my example. false values in the ReadOnly table can be clobbered. Here is a corrected version.

$ cat ro.lua
-- make some global variables readonly

local ReadOnly = {
  x = 5,
  y = 'bob',
  z = false,
}

local function check(tab, name, value)
  if ReadOnly[name] ~= nil then
    error(name ..' is a read only variable', 2)
  end
  rawset(tab, name, value)  -- tab[name] = value
end

setmetatable(_G, {__index=ReadOnly, __newindex=check})

$ lua -i ro.lua
> = x, y ,z
5       bob     false
> x = 4
stdin:1: x is a read only variable
stack traceback:
        [C]: in function `error'
        ro.lua:12: in function <ro.lua:10>
        stdin:1: in main chunk
        [C]: ?
> z = 1
stdin:1: z is a read only variable
stack traceback:
        [C]: in function `error'
        ro.lua:12: in function <ro.lua:10>
        stdin:1: in main chunk
        [C]: ?
> a = 2
> = x, y, z, a
5       bob     false   2
>


You've brought up a number of good points in the past. We should summarize them on a TipsAndTricks wiki page.

I'm thinking of things like:

function vec(...) return arg end

and

$ lua
Lua 5.0  Copyright (C) 1994-2003 Tecgraf, PUC-Rio
>
> for n,v in { one=1, two=2 } do
>> local v = v  -- need this
>> _G[n] = function() return v end
>> end
>
> = one(), two()
1       2
> for n,v in { one=1, two=2 } do _G[n] = function() return v end end
> = one(), two()
nil     nil
>

- Peter Shook