Does Pico-8 have the equivalent of this? It's a tool I tend to use a lot in projects. Or is this a function I have to create by nesting conditionals?



Lua does not have a switch statement. Discussion and a variety of suggestions here, most notably a lookup table: http://lua-users.org/wiki/SwitchStatement



Well, I typically use mine with probabilities and shuffled arrays.
So, basically I am gonna have to devise one if I want to use it, huh?



Try this one
-- fct to simulate a switch function switch(t) t.case = function (self,x) local f=self[x] or self.default if f then if type(f)=="function" then f(x,self) else error("case "..tostring(x).." not a function") end end end return t end |
usage
a = switch { [1] = function (x) print(x,10) end, [2] = function (x) print(x,20) end, default = function (x) print(x,0) end, } a:case(2) -- ie. call case 2 a:case(9) |
It's at the above link.
But I had it bookmarked here:
https://gist.github.com/picsoung/8e04fac92f883b3c9d77



Well, I'm trying to use it to define things within a function, without eating a fuckton of tokens calling the function in every outcome.
For example:
I have 6 doorways, A B C X Y Z (three on the left, three on the right). Each time I hit a "doorway," it turns that "exit" into a start point, and picks a new, different endpoint. This is the first place I use the switch. IE: switch(startdoor) ... case A, case B, case C... switch(exitdoor) nested within.
Now that the "exit doorway" is determined, I'm aiming to make a direct, "risky route" of level pieces to the next one; and then a second, less direct "safe route" to get to it a different way. This uses a Perlin noise style approach - adding each direction to the passageways totals a value that I'm using to recall level chunk data (1 = up, 2 = left, 4 = right, 8 = down) to an array.
Drawing the level is a second case where I use switch; by referencing the PN as input: case 9, for instance, is a passageway that's vertical. So I would simply use the switch to reference the tile data, or the mget. The idea here, for instance, is that one 9-character array can produce a 3x3 screen map (or other variants like this); and a second one can produce a layer of extra hazards and rewards (again, according to the first array's data) associated with taking the riskier route. And then tying these steps together into a single function that's only called when you start a session, or when you reach an exitdoor object.
Other places I tend to use them are with probabilities and shuffled lists/arrays; which tend to reference variables more than functions; and are simply nested within the functions themselves. I know seeding and rnd can be used for the first, but the shuffled lists are a different kind of beast. I suppose shuffling the variables that reference the list would be identical, but it would still require a for-do loop that takes it from a "default" order and arranges them to a shuffled one.
[Please log in to post a comment]