I want to make a TextBox where the player writes a function (of a module I made) and the function executes, but I don’t know how I make that.
So, I need to know how I make a script to execute functions that are written on a textbox.
Just say how I can do it or a part of the script that could help me.
function setMap()
end
local commands = {
KillEveryone = function() --[[Kill all players in the game]] end,
RestartGame = function() end,
SetMap = setMap,
}
function handleCommandBoxEnterPressed(text)
local command = commands[text]
if command then
command()
end
end
You can make a super simple command language that just takes the first word as the command name and every subsequent word as a string parameter:
--Iterator over single-space-separated words in a string.
function words(str)
local i = 1
local len = str:len()
return function()
if i > len then return nil end
local iSpace = str:find(" ", i) or len
local word = str:sub(i, iSpace )
i = iSpace + 1
return word:gsub(" $", "") --Remove the trailing space, if any
end
end
--Return a table containing every item visited by an iterator
function collect(iter)
local items = {}
for item in iter do
table.insert(items, item)
end
return items
end
--Returns the command name and a list of command parameters (as strings) given a command.
function parseCommand(commandText)
--Replace all multi-whitespace with a single space
commandText = commandText:gsub("%s%s*", " ")
local commandWordsIter = words(commandText)
local commandName = commandWordsIter() --Get the first word
local commandArgs = collect(commandWordsIter) --Get the subsequent words
return commandName, commandArgs
end
function parseArgNothing(...)
assert(select("#", ...) == 0, "Expected some number of arguments, got more!")
end
local commands = {
heal = function(player, amount, ...)
parseArgNothing(...)
--player = parseArgPlayer(playerName) --Optionally write some functions to validate the string arguments, and optionally do some error handling like showing the user an error message.
--amount = parseArgNumber(amount)
print(("Healing %s for %g health."):format(player, tonumber(amount)))
end,
kick = function(player, ...)
parseArgNothing(...)
--player = parseArgPlayer(player)
--kick logic
end,
kickAll = function(...)
--etc...
end
}
function executeCommand(commandName, args)
local command = commands[commandName]
assert(command ~= nil, ("Invalid command %s!"):format(commandName))
command(table.unpack(args))
end
executeCommand(parseCommand("heal Emma 55.125"))
executeCommand(parseCommand("kick Emma a")) --errors
executeCommand(parseCommand("kickall"))
executeCommand(parseCommand("hetajekhrakjhe")) --errors
executeCommand(parseCommand(commandTextBox.Text))