1
votes

I'm developing a roguelike in Lua for iOS and OSX. Pretty new to Lua and discovered to my dismay how nonrandom math.random is on my platform. I already had already setup my calls for random numbers set up through a function:

function rollD(max)
   return math.random(max)
end

So I found a fantastic answer in response to this post which turns out I think will solve my problem (it's pretty critical for a roguelike that the game be different each time) But in order to make the following tweaked function:

function rollD(max)
    return srandom(seedobj,1,max)
end

work, I had to make:

local seedobj = { seed = -232343 }

from Donati's Knuth adaptation not be local anymore, and then actually modified it to use (os.time()*-1). This actually works perfectly so far and my (very rudimentary) roguelike is rolling up random bad guys and dungeons just like I want it to. But I worry when things work right...

With a high number of calls to srandom (probably upwards of a thousand calls per level) am I going to take some kind of performance hit by having seedobj be global? I would like to think that, because it's nested in the table, that seed is a reference and that I'm worrying for nothing. But otherwise: is there a way I should modify this function so I can call it more efficiently?

1
The right way of crediting a person is to accept their answers and/or upvote their questions/answers (this latter can be done when you reach at least 15 rep points). Thanking a person in the text of a question/answer is not acceptable (it adds useless clutter in the Q/A). Sometimes a comment can be used (especially if you want to underline why an answer was useful), but don't abuse them for simple "thanks" (or say "thanks" and remove the comment after a couple of days). So please edit your question to remove the praises (I appreciate them, but they don't belong there). - Lorenzo Donati -- Codidact.com

1 Answers

2
votes

Accessing a global variable in Lua is like accessing a table field. If seedobj is global the following code:

function rollD(max)
    return srandom(seedobj,1,max)
end

in Lua 5.2 is equivalent to:

function rollD(max)
    return srandom(_ENV.seedobj,1,max)
end

or in Lua 5.1 is (roughly) equivalent to

function rollD(max)
    return srandom(_G.seedobj,1,max)
end

Where _ENV is the variable holding the current environment table and _G is the variable holding the global table.

Therefore whenever you call rollD you incur a small performance penalty for that indirect access, compared to a local variable. In general this penalty is significant or not depending on the complexity of the other operations performed when you call rollD.

In your specific case that penalty is unlikely to be noticeable, since the srandom implementation already performs much more intensive computations (among which some table accesses as well).