Table as member variable seems to be always nil

时间:2016-01-17 18:54:55

标签: lua lua-table

I'm new to lua and I'm trying to understand their OOP approach. I have this WebServerClient object which receives the socket from a client that connects to a webserver:

WebServerClient = {}
local WebServerClient_mt = { __index = WebServerClient }

function WebServerClient:Create(socket)
    local self = setmetatable({
        socket = socket,
        buffer = "test",
        header = {},
    }, WebServerClient_mt)
    socket:on("receive", function(socket, data)
        print(self.buffer)
        self.header:insert(data) -- PANIC happens on this line!
        self:onData(data)
    end)
    return self
end

The problem is that, once the client sends some data, I get the error:

PANIC: unprotected error in call to Lua API (WebServerClient.lua:20: attempt to call method 'insert' (a nil value))

So, it seems like self.header is nil, while I think it should be a valid table. Before the panic, test is printed to the console, so I'm pretty sure self is initiated correctly. (data is not nil as I can print it).

I'm using Lua 5.1.

Anyone knows what is happening?

1 个答案:

答案 0 :(得分:2)

self.header不是有问题的nil值。 nil值为self.header:insertheader是一张表,但它是空表。因此,header.insertnil

如果您尝试调用Lua标准函数table.insert,则无法通过实际表调用该函数。您必须像table.insert(tbl, value)一样调用它,其中tbl是您要插入的表。

表格不像字符串,您可以通过元方法从string库中调用函数。