我正在寻找 lua 中的库/函数,它允许您拥有自定义变量类型(甚至使用“type”方法检测为您的自定义类型)。我正在尝试制作一个具有自定义类型“json”的 json 编码器/解码器。我想要一个可以单独在 lua 中完成的解决方案。
问问题
6788 次
2 回答
15
您无法创建新的 Lua 类型,但您可以使用元表和表在很大程度上模仿它们的创建。例如:
local frobnicator_metatable = {}
frobnicator_metatable.__index = frobnicator_metatable
function frobnicator_metatable.ToString( self )
return "Frobnicator object\n"
.. " field1 = " .. tostring( self.field1 ) .. "\n"
.. " field2 = " .. tostring( self.field2 )
end
local function NewFrobnicator( arg1, arg2 )
local obj = { field1 = arg1, field2 = arg2 }
return setmetatable( obj, frobnicator_metatable )
end
local original_type = type -- saves `type` function
-- monkey patch type function
type = function( obj )
local otype = original_type( obj )
if otype == "table" and getmetatable( obj ) == frobnicator_metatable then
return "frobnicator"
end
return otype
end
local x = NewFrobnicator()
local y = NewFrobnicator( 1, "hello" )
print( x )
print( y )
print( "----" )
print( "The type of x is: " .. type(x) )
print( "The type of y is: " .. type(y) )
print( "----" )
print( x:ToString() )
print( y:ToString() )
print( "----" )
print( type( "hello!" ) ) -- just to see it works as usual
print( type( {} ) ) -- just to see it works as usual
输出:
表:004649D0 表:004649F8 ---- x 的类型是:frobnicator y 的类型是:frobnicator ---- Frobnicator 对象 字段 1 = 无 字段2 = 无 Frobnicator 对象 字段 1 = 1 字段2 = 你好 ---- 细绳 桌子
当然,这个例子很简单,关于 Lua 中的面向对象编程还有很多话要说。您可能会发现以下参考资料很有用:
- Lua WIKI OOP 索引页。
- Lua WIKI 页面:面向对象教程。
- Lua 编程的 OOP 章节。这是第一本书的版本,所以它侧重于 Lua 5.0,但核心材料仍然适用。
于 2013-10-13T19:04:54.600 回答
5
您要求的内容是不可能的,即使使用 C API 也是如此。Lua 中只有内置类型,没有办法添加更多。但是,使用元方法和表,您可以制作(创建函数)非常接近于其他语言中的自定义类型/类的表。例如,参见《Lua 中的编程:面向对象的编程》(但请记住,这本书是为 Lua 5.0 编写的,因此某些细节可能已更改)。
于 2013-10-13T18:38:45.337 回答