lua-users home
lua-l archive

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




On 16/07/16 06:32 AM, 书呆彭, Peng Yi wrote:
在 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.

I'll leave this here

---------------------
local i = 100
local f = 100.0

print(math.type(i), math.type(f)) --> integer float
assert(math.type(i) ~= math.type(f))

local t = {}

t[i] = "__key just expands this idea to userdata"

print(t[f]) --> __key just expands this idea to userdata
---------------------

They're not the same type, yet they compare equal and they access the same key. Given these semantics, I don't see why userdata shouldn't have them.

-------------------------
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()
-------------------------


--
Disclaimer: these emails may be made public at any given time, with or without reason. If you don't agree with this, DO NOT REPLY.