自定义变量类型 Lua

我正在寻找一个在 Lua 中允许你拥有自定义变量类型的库/函数(甚至可以使用“type”方法检测为你的自定义类型)。 我正在尝试制作一个具有自定义类型“json”的 JSON 编码器/解码器。我希望找到一个仅使用 Lua 就可以解决的方法。

点赞
用户2128694
用户2128694

将下面翻译成中文并且保留原本的 markdown 格式

你所要求的是不可能的,即使使用 C API 也无法实现。在 Lua 中,只有内置类型,无法添加任何其他类型。但是,使用元表和表,您可以制作(创建函数)非常接近其他语言中的自定义类型/类的表。例如,可以参考《Programming in Lua:面向对象编程》(但请记住,该书是为 Lua 5.0 编写的,因此有些细节可能已发生变化)。

2013-10-13 18:38:45
用户2633423
用户2633423

你不能创建新的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  -- 保存 `type` 函数
-- 猴子补丁 type 函数
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!" ) )  -- 只是为了查看它是否像往常一样工作
print( type( {} ) )  -- 只是为了查看它是否像往常一样工作

输出:

table:004649D0
table:004649F8
----
The type of x is: frobnicator
The type of y is: frobnicator
----
Frobnicator object
  field1 = nil
  field2 = nil
Frobnicator object
  field1 = 1
  field2 = hello
----
string
table

当然,这个示例是简单的,关于Lua面向对象编程还有更多要说的事情。你可能会发现以下参考资料有用:

2013-10-13 19:04:54