hi people
i would like to know if it is possible to assign a string representing valid Nimrod code and use it to execute the statement
i actually tried to use the emit template but it can only take static strings as parameters
an exemple of what i would like to do is
var instructions = ["CLD", "BCS", "NOP"]
the value contained in the local variable stmt is not static, so emit will throw an error
i already tried to declare a static variable, but it cant be dynamically assigned so there's no point in doing that
is there an other way to accomplish that ?
thanks,
Rational
I'm not 100% certain what your intent here is. If you want to dispatch to a function based on the name of a string, the following works:
import tables
var instructions = ["CLD", "BCS", "NOP"]
proc NOP() =
echo "does nothing"
proc BCS() =
echo "also does nothing"
proc CLD() =
echo "still does nothing"
let dispatcher = {"NOP": NOP, "CLD": CLD, "BCS": BCS}.toTable
proc execute_stmt() =
var stmt = instructions[2]
dispatcher[stmt]()
execute_stmt()
You can also use a macro to generate the table automatically, e.g.:
import tables, macros
const instructions = ["CLD", "BCS", "NOP"]
proc NOP() =
echo "does nothing"
proc BCS() =
echo "also does nothing"
proc CLD() =
echo "still does nothing"
macro createDispatcher: expr =
var code = "{"
for name in instructions:
code.add "\"" & name & "\": " & name & ","
code.add "}.toTable"
return parseExpr(code)
let dispatcher = createDispatcher()
proc execute_stmt() =
var stmt = instructions[2]
dispatcher[stmt]()
execute_stmt()
What you cannot do is generate code at runtime; that's simply not possible in a statically compiled language (well, until/if Nim gets a JIT compiler or interpreter or with the JS backend).