about summary refs log tree commit diff stats
path: root/lua/chupacabra/test_chupacabra.lua
blob: e2f54b1913c9ab7909b5e37d5e3796b7bdd28045 (plain) (blame)
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
local chupacabra = require("chupacabra") 

-- convert a table to a string
local function table_to_string(t)
    local str = "{"
    for i, v in ipairs(t) do
        if i > 1 then
            str = str .. ", "
        end
        str = str .. tostring(v)
    end
    str = str .. "}"
    return str
end

-- test cases
local function tc(input, expected_output)
    local output = chupacabra.run(input, {})
    local expected_output_str = type(expected_output) == "table" and table_to_string(expected_output) or tostring(expected_output)
    local output_str = type(output) == "table" and table_to_string(output) or tostring(output)
    assert(output_str == expected_output_str, "Test failed: " .. input .. " => " .. output_str .. ", expected: " .. expected_output_str)
    print("Test passed: " .. input .. " => " .. output_str)
end

tc("[1 1 1] [2 3 4] @+", {3, 4, 5})
tc("[1 1 1] 2 @+", {3, 3, 3})
tc("[2 3 4] 3 @-", {1, 0, -1})
tc("[2 3 4] 3 @*", {6, 9, 12})
tc("[2 3 4] [2 3 4] @*", {4, 9, 16})
tc("2 [12 6 4] @/", {6.0, 3.0, 2.0})
tc("[2 2 2] [24 12 16] @/", {12.0, 6.0, 8.0})
tc("1", 1)  -- 1
tc("2 1 .", 2) -- 2
tc("[1 2 3 4] 3 .", {1, 2, 3, 4})
tc("1 [1 2 3 4] .", 1)
tc("[1 1]", {1, 1})
tc("3 4 +", 7)  -- 3 + 4 = 7
tc("5 2 -", 3)  -- 5 - 2 = 3
tc("2 3 *", 6)  -- 2 * 3 = 6
tc("8 2 /", 4.0)  -- 8 / 2 = 4
tc("2 3 4 + *", 14)  -- 2 * (3 + 4) = 14
tc("5 2 3 + 4 + +", 14)  -- 5 + 2 + 3 + 4 = 14
tc("7 2 + 3 4 + +", 16)  -- 7 + 2 + 3 + 4 = 16
tc("5 2 - 3 4 * +", 15)  -- (5 - 2) + (3 * 4) = 15
tc("8 2 / 3 4 * +", 16.0)  -- (8 / 2) + (3 * 4) = 16
tc("1 2 3 4 5 ..", {1, 2, 3, 4, 5}) -- construct an array 
tc("[1 2 3 4 5] [6 7 8 9 10] [10 11 12 13] @..", {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 11, 12, 13}) -- combine arrays
tc("[10 20 30] 1 @", 10)  -- access array element at a given index (1-based)
tc("[10 20 30] 2 @ 20 +", 40)  -- this leaves nothing on the stack, since @ consumes the array and doesn't replace it on to the stack
tc("1 2 3 : +", 6) -- : duplicates the top element on the stack
tc("100 10 20 ?", 10) -- ? swaps the top two elements on the stack
tc("1 1 =", true) -- = compares the top two elements on the stack
tc("1 2 =", false)
tc("[1 2 3] [1 2 3] =", false) -- arrays are not equal, but their values can be
tc("[1 2 3] [1 2 3] @=", {true, true, true})
tc("[1 2 3] [1 2 4] @=", {true, true, false})