Posted 07 December 2016 - 09:24 PM
Would anyone be interested in some brick-like framework/utility/whatever-you-call-it?
Here is a simple example game (guess-the-number) which is using this script (Which I dubbed "Renga": That's Japanese for "brick")
And here is the corresponding code:
Some things you might notice in this code example are:
The state is the only thing persisting between the UI and the logic. Everything else is(/should be) local to the function and won't leak outside. If you try to set a value in the state to something else it also typechecks so you can't sneak in some weird type changes. This won't eliminate the problem with types entirely, but at least enforce consistent types used for the main "state" of the program. "nil" translates to "use the value from the last state" when returning a new state in the logic function.
Thanks to this "state enforcement" debugging programs using this becomes a breeze because you are able to store the states in a history and effectively "roll back the time". Or make it run step-wise.
Every input would be appreciated!
Here is a simple example game (guess-the-number) which is using this script (Which I dubbed "Renga": That's Japanese for "brick")
And here is the corresponding code:
Spoiler
local renga = dofile "renga"
local function processEvents (state, ...)
local args = {...}
if args[1] == "char" then
local ok, err = pcall(function() tostring(args[2]) end)
if(ok) then
if(tonumber(args[2]) == state[1]) then
return {nil,state[1],true}
end
return {nil,tonumber(args[2]),nil}
end
end
return state
end
local function UI (state)
if state[3] then
Center "You did it! It was %1%."
else
if(state[2] == -1) then
Center "Press a number to start guessing!"
else
Center "Looks like it wasn't %2%."
end
end
end
local app = {
appHandleEvent = processEvents,
appDrawUI = UI
}
renga(app, {math.random(1,9),-1,false})
Some things you might notice in this code example are:
- There are custom functions like "Center" which, well… renders the text at the center of the screen, I guess
- Strings written to the terminal using "Center" allow you to automatically interpolate from the state
- The UI is separated from the logic itself
The state is the only thing persisting between the UI and the logic. Everything else is(/should be) local to the function and won't leak outside. If you try to set a value in the state to something else it also typechecks so you can't sneak in some weird type changes. This won't eliminate the problem with types entirely, but at least enforce consistent types used for the main "state" of the program. "nil" translates to "use the value from the last state" when returning a new state in the logic function.
Thanks to this "state enforcement" debugging programs using this becomes a breeze because you are able to store the states in a history and effectively "roll back the time". Or make it run step-wise.
Every input would be appreciated!
Edited on 07 December 2016 - 08:31 PM