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.
In Lua, there is a function called 'type' that enables us to know the type of the variable. Some examples are given in the following code. By default, all the variables will point to nil until they are assigned a value or initialized. In Lua, zero and empty strings are considered to be true in case of condition checks.
There are eight basic types in Lua: nil, boolean, number, string, function, userdata, thread, and table. Nil is the type of the value nil, whose main property is to be different from any other value; it usually represents the absence of a useful value. Boolean is the type of the values false and true.
Lua is a dynamically typed language. There are no type definitions in the language; each value carries its own type.
In Lua, the following are the available string formatting syntax or string literals for different datatypes: %s : This serves as a placeholder for string values in a formatted string. %d : This will stand in for integer numbers. %f : This is the string literal for float values.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With