Log In  

When setting 2 table elements to the same function it returns the same output, I am trying to figure out how to "refresh" the function so it will generate a new random string each time I need to set a variable to that function. Provide below is said code; hopefully the comments make sense. Thanks In advance.

idtable={"aaaaaa","aaaaaa"}
id=""
i=0
x=0

function idgen()
 if i!= 3 then --i loop to generate 3 random numbers
  x=flr(rnd(16)) --picks a number between 0-15
  if (x<10) then --ensures single digits have 0 appended to the front to maintain fixed string length
   id=id.."0"..x
  else
   id=id..x
  end
  i+=1
 end    
return id
end

function _update()
end

function _draw()
cls()
idtable[1]=idgen(id) 
idtable[2]=idgen(id) --doesn't generate new random string

print(idtable[1],0,0,7)
print(idtable[2],0,8,7)
end
P#62972 2019-03-23 08:11

1

In LUA, all variables are global by default. This means that any time you reference a variable name, anywhere in your code, it will always point to the same spot in memory. What you need to do is move the declaration of id to inside of the function idgen, and put the local keyword in front of it, like this:

local id = ""

That way, every time the function gets called it will allocate a new local variable. Hope that helps.

P#62977 2019-03-23 16:36

Yes that definitely did help, thank you!

P#62985 2019-03-24 02:38

[Please log in to post a comment]

Follow Lexaloffle:          
Generated 2024-03-29 10:54:26 | 0.013s | Q:12