我有一个类似下面的Lua类。我使用json序列化对象并将其放在键值存储中。我能够序列化对象并将其成功放入键值存储,但在从键值存储中检索对象后,我无法调用该对象的任何方法。我理解json模块在编码时跳过方法,而我的对象在解码后没有方法。
在将对象从json解码为lua后,有没有办法将方法附加到类?有些东西类似于C语言中的函数指针。
local class_name = "user_object";
user_object = {}; --user class
function user_object.new (mobile, password, uid)
local self = {};
self.mobile = mobile;
self.uid = uid; -- generate a uid which is a running number.
self.password = password;
self.messages_sent = 0;
self.put_request_count = 0;
self.get_request_count = 0;
self.last_time_active = "";
self.get_tickets = {};
self.put_tickets = {};
self.group_message_stream = {};
self.group_ownerships = {}; -- group names which he is owner of
self.group_memberships = {}; -- group names which he is member of
self.sent_poke_count = 0;
self.sent_poke_stream = {};
self.recv_poke_count = 0;
self.recv_poke_stream = {};
function self:add_put_ticket(ticketid)
table.insert(self.put_tickets, ticketid);
self:incr_put_count();
self:save();
return;
end
function self:add_get_ticket(ticketid)
table.insert(self.get_tickets, ticketid);
self:incr_get_count();
self:save();
return;
end
答案 0 :(得分:2)
您可以使用元表来完成此操作。
user = { name = 'ponzao' } -- Just a table with values.
User = {} -- Table containing the functions.
function User:allCapsName() return self.name:upper() end -- A method.
setmetatable(user, {__index = User}) -- For unavailable keys all calls are dispatched to User.
print(user:allCapsName()) --> "PONZAO"
答案 1 :(得分:2)
Lua中的函数是第一类对象,可以在任何变量中存储函数。这条线
function self:add_put_ticket(ticketid)
相当于
self.add_put_ticket = function (self, ticketid)
从那里开始,应该明白该做什么:在可以访问的地方定义所需的方法,并在反序列化后将它们分配到适当的字段