我在lua中寻找一个库/函数,允许你有自定义变量类型(甚至可以使用“type”方法检测为自定义类型).我正在尝试制作一个自定义类型为“json”的json编码器/解码器.我想要一个只能在lua中完成的解决方案.
解决方法
您无法创建新的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中有很多关于面向对象编程的话要说.您可能会发现以下参考资料有用:
> Lua WIKI OOP index page.
> Lua WIKI page: Object Orientation Tutorial.
> Chapter on OOP of Programming in Lua.这是第一本书版本,因此它专注于Lua 5.0,但核心材料仍然适用.