lua-users home
lua-l archive

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


在 2016/7/16 7:05, Tim Hill 写道:
if __key returns (say) 100 as the key, then that will collide with using the number 100 in the same table. Not good.

If I interpret the OP's intention correctly, this is the desired effect he wanted to achieve. e.g. make a `bignum` key
decay as a Lua number key when the value could be represented within a Lua number's range.

but I don't like this whole `__key` idea. the semantic of table key comparison is fine in current Lua. if you want to
have customized table look up behavior, you could just use a proxy table and `__index` metamethod.

it doesn't feel right to me. the following code should not have different semantics. I might use rawequal instead of ==,
but you get the idea of trading memory for speed.

-------------------------
if x == a1 then
   return action1()
elseif x == a2 then
   return action2()
elseif x == a3 then
   --[[...]]
else
   return default_action()
end
-------------------------


-------------------------
local actions = {
    [a1] = action1(),
    [a2] = action2(),
    [a3] = --[[...]]
}
local action = actions[x] or default_action

return action()
-------------------------

--
the nerdy Peng / 书呆彭 / Sent from Thunderbird