我在lua中寻找一个库/函数,允许你有自定义变量类型(甚至可以使用“type”方法检测为自定义类型).我正在尝试制作一个自定义类型为“json”的json编码器/解码器.我想要一个只能在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,但核心材料仍然适用.