mario::konrad
programming / C++ / sailing / nerd stuff
Lua Number Class
© 2005 / Mario Konrad

Demo of a class num representing a number which implements basic math operations. This is a mini object oriented demo with Lua.

num.lua:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
num = {}

num_mt = {
    __newindex = function(t, k, v) error('not permitted to create field \'' .. k .. '\'') end,

    __index = num,
    __add = function(a, b) return setmetatable({ v = a.v + b.v }, num_mt) end,
    __sub = function(a, b) return setmetatable({ v = a.v - b.v }, num_mt) end,
    __mul = function(a, b) return setmetatable({ v = a.v * b.v }, num_mt) end,
    __div = function(a, b) return setmetatable({ v = a.v / b.v }, num_mt) end,
    __mod = function(a, b) return setmetatable({ v = a.v % b.v }, num_mt) end,
    __pow = function(a, b)
            if type(b) == type(num) then
                    return setmetatable({ v = a.v ^ b.v }, num_mt)
            else
                    return setmetatable({ v = a.v ^ tonumber(b) }, num_mt)
            end
    end,
    __eq  = function(a, b) return a.v == b.v end,
    __lt  = function(a, b) return a.v <  b.v end,
    __le  = function(a, b) return a.v <= b.v end,
    __gt  = function(a, b) return a.v >  b.v end,
    __ge  = function(a, b) return a.v >= b.v end,

    __tostring = function(a) return tostring(a.v) end,
}

function num:new(val)
    return setmetatable({ v = val }, num_mt)
end

function num:val()
        return self.v
end

a = num:new(10)
b = num:new(20)
c = num:new(3)
print(a:val(), b:val(), (a+b):val(), (a*b):val(), (a ^ 2):val(), (a ^ c):val())