huysentruitw
huysentruitw

Reputation: 28151

Table as member variable seems to be always nil

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?

Upvotes: 0

Views: 118

Answers (1)

Nicol Bolas
Nicol Bolas

Reputation: 474316

self.header is not the nil value in question. The nil value is self.header:insert. header is a table, but it's an empty table. Therefore, header.insert is nil.

If you were trying to call the Lua standard function table.insert, you can't call that through the actual table. You have to call it like this table.insert(tbl, value), where tbl is the table you want to insert.

Tables aren't like strings, where you can call functions from the string library through metamethods.

Upvotes: 2

Related Questions