PDA

View Full Version : Dumb but quick LUA question...



Promixis
May 14th, 2003, 01:47 PM
I want to test to see if a variable has been initialized, and if not call the initialization routine...

init routine would be

init = 1

body of code would be

if init <> 1 then goto init routine.

Problem is ...

I can't fiquire out how to get lua to do the test!
If the variable has not been declared/used it will not allow me to use it in an if statement.

I know I must be missing something obvious - oh well, thats what happens with a weekend coder :)

Mike

JimHugh
May 14th, 2003, 03:12 PM
if not init == nil then
-- do code here
end

Promixis
May 15th, 2003, 02:58 AM
Thanks!

Bitmonster
May 15th, 2003, 09:25 AM
Actually this would not test the <>1 state but only if its nil. If you want your code only to happen if init is not 1 you can do it like this:

if init ~= 1 then
-- your code here
end
The ~= is LUAs way of saying the same as you would normaly do with <> or != in other languages.


In most cases it's easier and more clearly if you use a nil indicator for such cases. Let's say your init variable will also hold some value after your initialization code has been executed. If your script starts and the init variable was never used before, it actually has the nil value. So you can test:

if not init then
init = 1 -- or any other value you like, even 0
-- your additional initialization code
end
Your code gets only executed if init is nil. So if you want to initialize later again at the same point you can delete the variable. This is simply done by assigning the nil value, eg.:
init = nil

I hope I don't confused you to much, but it's important in LUA to understand the nil value. All logic operations use nil as false and every other value (the null also) as true. Additionally you have to know that a none existing variable has the nil value and also if you want to make a variable none existing you can simply assign nil to it.

The nil value is very special in LUA and only a small set of programming languages have a mechanism like this, so even skilled programmers need some time to get familiar with it. But it's also one of the most powerfull features of LUA.

Bitmonster

Promixis
May 15th, 2003, 05:58 PM
I really appreciate the great explanation!

How things have changed since my computer science days in the 80's :)

Mike