Roku Developer Program

Developers and content creators—a complete solution for growing an audience directly.
cancel
Showing results for 
Search instead for 
Did you mean: 
EnTerr
Level 8

Tips & Tricks: static/const variables for a function

I thought i'll share a code pattern for BS i came up with. It's not particularly deep but i haven't seen it shown in examples, so here it is:

You know how sometime in a function you have some chunk of data which is too big or too slow to build every time the function is called? Say the labyrinth structure of your Minotaur game or an external RSS feed, or the seed for that custom pseudo-random generator. Which can get stored as global variable but does not feel quite right since is of concern only to that one function... and maybe there will be a name clash, uhhh. Or you can always pass it as argument from top-level function, making it its concern... nah.

Okay... well if you think in Java terms, things seem clear - you need to create an Object to contain the data and make the function a method in it. That's legit but likely a case of Execution in the Kingdom of Nouns. If you come from Lisp background, you'd like a closure - but for better or worse* B/S has no closures nor lexical scopes. If you are C/C++, surely you will like a function-level static variables. What i came to use is in-between Lisp and C:
function workerBee():
'fetch const/static vars
o = m._workerBee
if o = invalid:
o = { }
o.separators = " '" + chr(34) + chr(9) + chr(10) + chr(13)
o.config = url_to_xml("http://mum.bo/jumbo")
m._workerBee = o
end if
separators = o.separators

'do what's due, using `separators` and `o.config`
' ...
end function

The idea is to store all such static variables in a global variable named like the function but prepended with underscore (as naming practice) and when the function is called, try to fetch first that variable from outside and if not available initialize it (so initialization happens once, on first use/as needed)

(I chose `o` as variable name because of how it's an encircles/enclosure for the vars but can of course be anything else like say `_`. Or even `m` - in which case we'll have a "pseudo-method" on our hands.)

(*) i'll argue it's for the better
0 Kudos