That’s a neat idea! I might use this in my own game!
Let’s make a 2D array called logicChain. This will hold our logic and respective results.
A conditional statement has two parts to it: a condition and a result. Let’s store those like this in the array: { {condition1, result1}, {condition2, result2}, … }
Now, we need a loop to go through the table and evaluate each condition. If we want to have an “else” statement at the end, we can just put it as the last entry in the table and have the condition just set to true, so it will execute if nothing else in the table does.
We also need to provide a noMatchResult in case none of our conditions match. nil seems intuitive to me in most cases, but sometimes you may need to use something else.
I believe the condition will evaluate as soon as you declare the logic table, so you need to re-create the table each time you call it.
function evaluateLogicTable(logicTable, noMatchResult)
local logicTableEvalIndex = 1
while (logicTableEvalIndex <= #logicTable) do
if logicTable[logicTableEvalIndex][1] then
return logicTable[logicTableEvalIndex][2]
end
logicTableEvalIndex = logicTableEvalIndex + 1
end
return noMatchResult
end
local x = 3
local logicTable = { {(x > 4), “X is greater than 4”}, {(x > 2), “X is greater than 2”}, {true, “An else condition if we want one”} }
print(evaluateLogicTable(logicTable, nil))
-- Will output “X is greater than 2”
local x = 5
print(evaluateLogicTable(logicTable, nil))
-- Will output “X is greater than 2”, since the original logicTable does NOT get re-evaluated until it gets reassigned
logicTable ={ {(x > 4), “X is greater than 4”}, {(x > 2), “X is greater than 2”}, {true, “An else condition if we want one”} }
print(evaluateLogicTable(logicTable, nil))
-- Will now output “X is greater than 4” as we expect since the conditions have been re-evaluated
———————————
To make life easier for you, just use a function that resets/re-evaluates your logic table every time you need it:
-- Updating by function call (RECOMMENDED)
function getMyLogicTable()
return { {(x > 4), “X is greater than 4”}, {(x > 2), “X is greater than 2”}, {true, “An else condition if we want one”} }
end
logicTable = getMyLogicTable()
-- Updating by global variable
logicTable = nil
function getMyLogicTable()
logicTable = { {(x > 4), “X is greater than 4”}, {(x > 2), “X is greater than 2”}, {true, “An else condition if we want one”} }
end
getMyLogicTable()