Page 1 of 1

How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 4:39 am
by TopDole
I read most of the lua book a while back and have been coding for quite a while but i havent found out how to define multiple variables yet. Does anyone know? Is it even possible?

A couple things I tried that I wish worked:

P1.x, P2.x, P3.x, P4.x = 0
P1.x = P2.x = P3.x = P4.x = 0

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 6:09 am
by Wojak

Code: Select all

P1.x, P2.x, P3.x, P4.x = 0,0,0,0
http://www.lua.org/pil/4.1.html

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 9:05 am
by zorg
You can define multiple vars as how Wojak wrote, but you cannot assign one thing to multiple variables at once.

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 9:38 am
by s-ol
zorg wrote:You can define multiple vars as how Wojak wrote, but you cannot assign one thing to multiple variables at once.
You can write a helper though:

Code: Select all

function all( val, num ) 
 local r = {} 
 for i=1,(num or 10) do
  r[i] = val
 end
 return unpack(r)
end

-- use
local a, b, c, d, e = all( 0 ) -- for up to 10 vars
local a, b, C = all( 0, 3 ) 

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 10:19 am
by Muris
I know this is bit of a derailing thing, but one of the best things I've found about lua is as following:

Code: Select all

 x, y = y, x 

The swapping is just so brilliant compared to other languages where you usually end up writing a helper function to do it.

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 10:42 am
by zorg
S0lll0s wrote: code-snip
Don't forget to

Code: Select all

return unpack(r)
in that helper function though, else anything you define with that will be nil :3
Also our postcounts were in sync, and will be again if you reply :D

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 12:14 pm
by s-ol
-*Accidental double submit -

Re: How do i define multiple variables at once?

Posted: Thu Dec 04, 2014 12:15 pm
by s-ol
zorg wrote:
S0lll0s wrote: code-snip
Don't forget to

Code: Select all

return unpack(r)
in that helper function though, else anything you define with that will be nil :3
Also our postcounts were in sync, and will be again if you reply :D
Whoops, That's what I get for coding on mobile...
yaaaaay :ultrahappy: