开发者

Lua metatable question

I have a working defined metatable (see below), but I cannot make it behave开发者_Python百科 like I would like it to. When I feed a set of values to ht.array (see below) it works fine. When I try to give it a table, it doesn't work obviously since it expects a range of values and not a nested table. But, even if I modify ht.array to get rid of the nested table (like a = a[1]) it does not work. Any ideas? Would be greatly appreciated! In summary what I'm aiming for is v1 = ht.array{{1,2,3}}, where it would work when I do v1 + v1.

ht = {}
local mt = {}

function ht.array (a)
    array = {} 
    setmetatable(array, mt)
    for k, v in ipairs(a) do
        array[k] = v
    end
    return array
end

function ht.add (a, b) 
    local res = ht.array{}
    for k in pairs(a) do res[k] = a[k] + b[k] end
    return res
end

mt.__add = ht.add

-- This works
v1 = ht.array{4,5,6}
v2 = ht.array{3,45,90}

c = v1 + v2

for k, v in ipairs(c) do
    print(v)
end

-- But this does not work
a = {3,4,5}
b = {9,1,11}
v1 = ht.array{a}
v2 = ht.array{b}

c = v1 + v2

for k, v in ipairs(c) do
    print(v)
end


First, why not just do this?

v1 = ht.array(a)
v2 = ht.array(b)

This way you are calling the "array" function (weird name by the way) with tables rather than single-element tables containing another table. But if you do want it to support single-element tables containing another table, you could add this quick hack to the top of ht.array:

if type(a[1]) == 'table' then
    a = a[1]
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜