I am looking for a library/function in lua that allows you to have custom variable types (even be detected as your custom type using the "type" method). I'm trying to make a json encoder/decoder that has the custom type "json." I want a solution that can be done in lua alone.
2 Answers
You cannot create new Lua types, but you can mimick their creation to a good extent using metatables and tables. For example:
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
Output:
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
Of course the example is simplistic and there are more things to say about object oriented programming in Lua. You may find the following references useful:
- Lua WIKI OOP index page.
- Lua WIKI page: Object Orientation Tutorial.
- Chapter on OOP of Programming in Lua. It is the first book edition, so it is focused on Lua 5.0, but the core material still applies.
3 Comments
jsonCode = {"json text here"} varType(jsonCode, "json") would return simply jsonCode with the custom type "json". tostring(jsonCode) would just return jsonCode[1] (which would, in this case, be equal to "json text here"). Don't bother to implement the 2-value system you have here, I will only be using it with table that have 1 value.What you are asking for is not possible, not even with the C API. There simply are only the builtin types in Lua, there is no way of adding more. However, using metamethods and tables you can craft (functions creating) tables that come very close to custom types/classes in other languages. See for example Programming in Lua: Object-Oriented Programming (but keep in mind that the book was written for Lua 5.0, so some details might have changed).