String to commands
BlitzMax Forums/BlitzMax Programming/String to commands
| ||
| Hi all, in Blitz is there a way to convert user inputed strings to commands? So that rather than typing if string_in = stringcommand1 then command1 if string_in = stringcommand2 then command2 ... you can type for a$ = eachin list_of_accepted_commands if a$ = string_in then run string_in next so that after checking to see if it is valid the program will literally run the string. |
| ||
| No -- since Blitz code gets converted to machine language at compile time, the blitz commands cease to exist at that point. If you want to run code, you'll probably have to work with a scripting language like LUA (there's several LUA modules available for BlitzMax) |
| ||
For simple cases you can do something like this:Type Command Abstract
Method Run:Object(args:Object[]) Abstract
End Type
Type Command1 Extends Command
Method Run:Object(args:Object[])
Print "we're in command 1"
End Method
End Type
Type Command2 Extends Command
Method Run:Object(args:Object[])
Print "doing something else"
Return args[2].ToString()
End Method
End Type
Local commandMap:TMap = CreateMap()
For Local c:String = EachIn ["Command1", "Command2"]
commandMap.Insert(c, TTypeId.ForName(c).NewObject())
Next
'...
Local cmd:String = Input(...etc
Local arg0:String = Input(...etc
Local result:Object = Command(commandMap.ValueForKey(cmd)).Run([arg0])You can extend this idea with e.g. metadata declarations to easily and automatically verify the size of the argument arrays. This will handle basic commands with simple arguments (no variable substitution). For something more complicated, like loops or custom function definitions, as xlsior says, a full scripting language is what you need. |