string_math.lua

by NihilisticPuffin
396 days agolua
COPY
1
args = {...}
2
local h = fs.open(args[1], 'r')
3
data = h.readAll()
4
h.close()
5

6
local old_mt = debug.getmetatable("")
7
local mt = {}
8
local error_msg = "attempt to perform arithmetic on %s and %s"
9
debug.setmetatable("",mt)
10
mt.__add = function (op1, op2)
11
    op1 = op1 or 'nil' op2 = op2 or 'nil'
12
    if ((type(op1) == 'table' or type(op1) == 'function') or (type(op2) == 'table' or type(op2) == 'function')) then error(string.format(error_msg, type(op1), type(op2)), 2) end
13
    return (type(op1) == 'boolean' and (op1 and 'true' or 'false') or op1)
14
    .. (type(op2) == 'boolean' and (op2 and 'true' or 'false') or op2)
15
end
16
mt.__sub = function (op1, op2)
17
    if(type(op1) == 'number') then
18
        return string.sub(op2, 1+op1, #op2)
19
    elseif(type(op2) == 'number') then
20
        return string.sub(op1, 1, #op1-op2)
21
    end
22
    return error(string.format(error_msg, type(op1), type(op2)), 2)
23
end
24
mt.__mul = function (op1, op2)
25
    if(type(op1) == 'number') then
26
        local tmp = ''
27
        for i=1, op1 do
28
            tmp = tmp .. op2
29
        end
30
        return tmp
31
    elseif(type(op2) == 'number') then
32
        local tmp = ''
33
        for i=1, op2 do
34
            tmp = tmp .. op1
35
        end
36
        return tmp
37
    end
38
    return error(string.format(error_msg, type(op1), type(op2)), 2)
39
end
40
mt.__div = function (op1, op2)
41
    if not type(op1) == 'string' then return error(string.format(error_msg, type(op1), type(op2)), 2) end
42
    if(type(op2) == 'number') then
43
        return {string.match(op1, string.rep(('('..string.rep(('.?'), op2)..')'), math.floor(#op1/(op2))))}
44
    elseif(type(op2) == 'string') then
45
        local match = "([^"..op2.."]+)"
46
        if op2 == '' then match = "(.*)" end
47
        local t={}
48
        for str in string.gmatch(op1, match) do
49
                table.insert(t, str)
50
        end
51
        return t
52
    end
53
    return error(string.format(error_msg, type(op1), type(op2)), 2)
54
end
55
mt.__mod = function (op1, op2)
56
    if not type(op1) == 'string' then return error(string.format(error_msg, type(op1), type(op2)), 2) end
57
    if(type(op2) == 'number') then
58
        return string.sub(op1, -(#op1%op2), -(#op1%op2))
59
    end
60
    return error(string.format(error_msg, type(op1), type(op2)), 2)
61
end
62
mt.__unm = function(op1)
63
    return string.reverse(op1)
64
end
65

66
loadstring(data)()
67

68
debug.setmetatable("", old_mt)