自定义变量类型Lua

时间:2013-10-13 18:32:04

标签: variables lua

我正在寻找lua中的库/函数,它允许您拥有自定义变量类型(甚至可以使用“type”方法检测为自定义类型)。我正在尝试制作一个自定义类型为“json”的json编码器/解码器。我想要一个只能在lua中完成的解决方案。

2 个答案:

答案 0 :(得分:13)

您无法创建新的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

<强>输出:

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中有很多关于面向对象编程的话要说。您可能会发现以下参考资料很有用:

答案 1 :(得分:5)

您要求的是不可能的,即使使用C API也是如此。 Lua中只有内置类型,没有办法增加更多内容。但是,使用元方法和表格,您可以制作(函数创建)表格,这些表格非常接近其他语言的自定义类型/类。请参阅示例Programming in Lua: Object-Oriented Programming(但请记住,本书是为Lua 5.0编写的,因此某些细节可能已更改)。

相关问题