lua-users home
lua-l archive

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

Just thought of another way to demonstrate the difference;

Consider that you wanted to be able to index individual characters in strings via
the usual method, that is

local temp = "hello"
assert(temp[3] == "l")

Lua is flexible enough that you can do that, via __index metamethods. You could

>  local mt = debug.getmetatable("")
>  local oldindex = mt.__index
>  mt.__index = function(str, key)
>    local num = tonumber(key)
>    if num then
>      return string.sub(str, num, num) 
>    else
>      return oldindex[key]
>  end

However now situations like

>  local i = key:find("h")

require one more function call then is necessary. It is, as far as I can tell,
impossible to avoid this with Lua, without modifying the vm.
The proposed change though, would allow a more efficient approach:

>  setmetatable(debug.getmetatable("").__index,
>    {__index = function(str, key)
>      local num = tonumber(key)
>      if num then
>        return str:sub(num, num)
>      end
>    end})

With this approach the function is only called if the key couldn't be found in
the standard __index metatable. It won't work without the vm modification though,
as the function would be passed the strings __index metatable instead of the
string itself.

Although the example here is for strings, the same advantages apply when using
tables in an object orientated approach, etc.

Anyways, I think I've made my case now.. probably more then once. Will leave it
to the powers that be to consider changing the implementation (although I imagine
they'll err on the side of caution, probably wise).

- Alex