2014-09-08 17 views
5

Jak zmienić operatora długości (#) dla tabeli w Lua, instrukcja sugeruje przypisanie funkcji __len w metatable, a następnie przypisanie tej metatabilitacji do tabeli, którą chcę przesłonić, ale to nie działa zgodnie z oczekiwaniami? Nie mam opcji, aby zastąpić to po stronie C.Zastępowanie funkcji długości tabeli Lua nie działa

turtles = {1,2,3} 
setmetatable(turtles, {__len = function(mytable) return 5 end}) 

print(#turtles) 
--returns 3, should return 5 
+0

możliwe duplikat [Lua override # dla ciągów] (http://stackoverflow.com/questions/23085204/lua-override-for-strings) –

+0

@LarryBattle Niezupełnie duplikatu, tutaj argumentu nie jest łańcuchem, ale tabelą. –

+0

Twój kod działa poprawnie w [Lua live demo] (http://www.lua.org/demo.html). – lhf

Odpowiedz

6

Musisz używać Lua 5.1. Metamethod __len na tabelach jest obsługiwany od wersji Lua 5.2.

W przypadku Lua 5.1 reference manual, jeśli operand jest tabelą, należy bezpośrednio zwrócić prymitywną długość tabeli.

"len": operacja #.

function len_event (op) 
    if type(op) == "string" then 
    return strlen(op)   -- primitive string length 
    elseif type(op) == "table" then 
    return #op    -- primitive table length 
    else 
    local h = metatable(op).__len 
    if h then 
     -- call the handler with the operand 
     return (h(op)) 
    else -- no handler available: default behavior 
     error(···) 
    end 
    end 
end 

W Lua 5.2 reference manual, jeśli argument jest stół, sprawdzić czy __len metamethod jest dostępna.

"len": operacja #.