The name for this interpreter… (shit code)
local function split(str, sep) -- string.split does not exist in Pure Lua
local fields = {}
local pattern = string.format("([^%s]+)", sep or " ")
str:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
local function interpreter(code_str)
local lines = {}
local stack = {}
local constants = {}
for line in code_str:gmatch("[^\r\n]+") do
table.insert(lines, line)
end
for stackline, line in ipairs(lines) do
local command, argument = line:match("^(%w+)%s*(.*)$")
local contents = split(argument, " ")
if command == "PRINT" then
if not stack[stackline] then
stack[stackline] = {["PRINT"] = {}}
end
local printOrder = 1
for _, constant in ipairs(contents) do
local found = false
for i = 1, #stack do
if stack[i]["LOCAL"][constant] then
stack[stackline]["PRINT"][printOrder] = {
name = constants[constant] or constant,
value = stack[i]["LOCAL"][constant]
}
found = true
printOrder = printOrder + 1
break
end
end
if not found then
print("Undefined variable or constant: " .. constant)
end
end
elseif command == "END" then
break
elseif command == "LOCAL" then
local value, content = contents[1], contents[2]
if not stack[stackline] then
stack[stackline] = {["LOCAL"] = {}}
end
stack[stackline]["LOCAL"][value] = content
constants[value] = value -- Store the constant name
else
print(command .. ":" .. stackline .. ": Incomplete statement: expected assignment or a function call")
stack = nil
break
end
end
return stack
end
local function execute_stack(stack)
if not stack then
return
end
for stackline, entry in ipairs(stack) do
if entry["PRINT"] then
for _, item in ipairs(entry["PRINT"]) do
print(item.name)
print(item.value)
print()
end
end
end
print(stack)
end
local code_str = [[
LOCAL HELLO GUYS
LOCAL THIS IS
LOCAL A TEST
PRINT HELLO THIS A
]]
local stack = interpreter(code_str)
execute_stack(stack)
-- Expected Output:
-- HELLO
-- GUYS
-- THIS
-- IS
-- A
-- TEST
-- (stack table)