I have tried again and again to get this code to work.
-- Sample assembly code with labels
local assemblyCode = [[
LOAD R1, 10
STORE R1, 20
ADD R1, 30
SUBTRACT R2, 40
JUMP_IF_ZERO R1, LOOP
HALT
LOOP:
ADD R2, R3
JUMP LOOP
]]
-- Mapping of assembly mnemonics to opcodes
local opcodeMappings = {
["NOOP"] = 0,
["LOAD"] = 1,
["STORE"] = 2,
["ADD"] = 3,
["SUBTRACT"] = 4,
["JUMP"] = 5,
["JUMP_IF_ZERO"] = 6,
["COMPARE"] = 7,
["MULTIPLY"] = 8,
["DIVIDE"] = 9,
["LOGICAL_AND"] = 10,
["LOGICAL_OR"] = 11,
["SHIFT_LEFT"] = 12,
["SHIFT_RIGHT"] = 13,
["HALT"] = 14,
["MOV"] = 15,
}
-- Mapping of register mnemonics to register numbers
local registerMappings = {
["R1"] = 0,
["R2"] = 1,
["R3"] = 2,
}
-- Process and assemble the code
function assemble(assemblyCode)
local assembledCode = {}
local labelTable = {}
for line in assemblyCode:gmatch("[^\r\n]+") do
local parts = {}
for part in line:gmatch("%S+") do
table.insert(parts, part)
end
if #parts > 0 then
local mnemonic = parts[1]:upper()
if mnemonic:sub(-1) == ":" then
local label = mnemonic:sub(1, -2)
labelTable[label] = #assembledCode + 1
else
local opcode = opcodeMappings[mnemonic]
if opcode then
local instruction = opcode * 32
if opcode == 0 then
-- NOOP
elseif opcode >= 1 and opcode <= 15 then
if opcode == 15 then
-- MOV
local srcRegister = registerMappings[parts[2]:upper()]
local destRegister = registerMappings[parts[3]:upper()]
if not srcRegister or not destRegister then
error("Invalid register in MOV instruction.")
end
instruction = instruction + (srcRegister * 4) + destRegister
else
local register = registerMappings[parts[2]:upper()]
local operand = tonumber(parts[3])
if not register or not operand then
error("Invalid register or operand.")
end
instruction = instruction + (register * 32) + operand
end
else
error("Invalid opcode: " .. mnemonic)
end
table.insert(assembledCode, instruction)
else
error("Unknown mnemonic: " .. mnemonic)
end
end
end
end
-- Replace label references
for i, instruction in ipairs(assembledCode) do
if type(instruction) == "string" then
local label = instruction
local labelAddr = labelTable[label]
if not labelAddr then
error("Label not found: " .. label)
end
assembledCode[i] = labelAddr
end
end
return assembledCode
end
-- Assemble the code
local assembledCode = assemble(assemblyCode)
-- Display the assembled machine code
for _, instruction in ipairs(assembledCode) do
if type(instruction) == "number" then
print(string.format("0x%04X", instruction))
else
print(instruction .. ":")
end
end
I have tried to get ChatGPT to fix it, but it refuses to work. It's meant to print the translated instructions off to the console (gonna use it elsewhere) but it keeps bringing up the register error I implemented as Workspace.Script:77: Invalid register or operand. I am running it with the Example code provided, any help welcome.
I wrote it in Lua instead of Luau, i had to rewrite the whole thing in the end