This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
TheGeek's profile picture

How do I run a command stored in a table as a string?

Started by TheGeek, 18 February 2013 - 02:49 PM
TheGeek #1
Posted 18 February 2013 - 03:49 PM
I wish to implement what I think is called an Object Oriented method, where all of the object's properties and what it does is stored in a table entry. The end goal is to create a function that can do any command I need without having to code for every possible command type. In this case, it would be a button that could be triggered by a touchscreen even that executes a command upon being pressed.

My code would be something like the following:

--Init variables
GUI = {button1={xMin = 1,xMax = 2, yMin = 1, yMax = 2,onPress="redstone.setBundledOutput("back", colors.white)"}}

--functions
function RangeXY(X, xMin, xMax, Y, yMin, yMax)
if X >= xMin and X <= xMax and Y >= yMin and Y <= yMax then --check if i got the "greater than or equal to" sign right!
  return true
else
  return false
end

function updateGUI(GUI)
--code goes here to draw button based on table entries in GUI
end

updateGUI(GUI)

--main loop
while true do

event, var1,var2,var3 = os.pullEvent()

if event == "monitor_touch" then --if event was a touchscreen input
  monitor, X, Y = var1,var2,var3
  for key, table in ipairs(GUI) do
   if RangeXY(X, table.xMin, table.xMax, Y, table.yMin, table.yMax) then --this would be true if the player clicked the screen within the button area
	dosomethingwith(table.onPress) -- this line will run the command stored as a string in the GUI table. WHAT MUST IT BE?
   end
 end
 updateGUI(GUI)
end

What command or function would allow me to run the command listed in the table button1.onPress?
Edited on 18 February 2013 - 02:59 PM
Sammich Lord #2
Posted 18 February 2013 - 03:52 PM
You can use:

loadstring("stringToRun")()
To run a string. For example if I want to run a string called "print('Hello world')" then I would do:

local run = "print('hello world')"
loadstring(run)()
Hope this helps.
remiX #3
Posted 18 February 2013 - 06:13 PM
GUI = {button1={xMin = 1,xMax = 2, yMin = 1, yMax = 2,onPress= function() redstone.setBundledOutput("back", colors.white) end}}

You make the onPress a function handler for what it must do, then when it's pressed you call it like a normal function:
GUI.button1.onPress()