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?
答案 0 :(得分:2)
self.header
不是有问题的nil
值。 nil
值为self.header:insert
。 header
是一张表,但它是空表。因此,header.insert
为nil
。
如果您尝试调用Lua标准函数table.insert
,则无法通过实际表调用该函数。您必须像table.insert(tbl, value)
一样调用它,其中tbl
是您要插入的表。
表格不像字符串,您可以通过元方法从string
库中调用函数。