4

Usually, I compare two floats by seeing if they are within a range of a very small number. It doesn't work for table keys because you do not know if they exist without knowing their key (if that makes sense).

Example with lua 5.1 on a 64 bit computer:

a, b, c = 1.7, -0.8, -0.4
d = a + b + c -- prevents constant folding
print(string.format('%1.20f', d)) --  0.49999999999999989000  (around 0.5)
assert(d ~= 0.5)
t = {[0] = 'foo', [0.5] = 'bar'}
print(t[d]) -- nil  (I want it to print 'bar')

Basically, how can I find a key in a table while accounting for floating point error? I'd want it to work without a comparison to each key in the table, so it can still be fast with big tables. There's probably already a built-in function to do this, but I could not find one.

Any help would be appreciated!

4

1 回答 1

4

如果您确实必须从来自不同来源的浮点数索引,我建议您将它们转换为固定格式的字符串,您希望保留尽可能多的小数位,并使用这些字符串索引表。

__newindex您甚至可以通过为代理表设置适当的元方法来自动实现这一点。

于 2012-10-11T01:41:31.127 回答