简体   繁体   中英

Lua attempt to call method a nil value

I'm lost on what I'm doing wrong here.

I have this simple code:

Queue = {}
Queue.__Index = Queue

function Queue.Create()
    local obj = {}
    setmetatable(obj, Queue)
    return obj
end

function Queue:PushBack(item)
end

q = Queue.Create()
print(q)
q:PushBack(1)

When executing this I get "attempt to call method 'PushBack' (a nil value). However, if I change the PushBack function like this and call it accordingly it works:

function Queue.PushBack(q, item)
end

q = Queue.Create()
print(q)
Queue.PushBack(q, 1)

The code runs and executes correctly. I understand that ":" is syntactic sugar, so it seems to me that

function Queue:PushBack(item)

would be exactly the same as

Queue.PushBack(q, item)

But it dies on me. Does it have to do with how I'm creating the object? I'm pretty lost on this and I can't seem to figure out what exactly is wrong.

The nil signifies that the PushBack function is not found in the first case.

The reason your code doesn't work, is because you have unintentionally misspelt __Index as it should be:

Queue.__index = Queue

with i of __index being lower-case.

Once corrected, your code should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM