Lua math.random explain - lua

sorry for asking this question but I couldn't understand it
-- but i don't understand this code
ballDX = math.random(2) == 1 and 100 or -100
--here ballDY will give value between -50 to 50
ballDY = math.random(-50, 50)
I don't understand the structure what is (2) and why it's == 1
Thank you a lot

math.random(x) will randomly return an integer between 1 and x.
So math.random(2) will randomly return 1 or 2.
If it returns 1 (== 1), ballDX will be set to 100.
If it returns 2 (~= 1), ballDX will be set to -100.
A simple way to make a 50-50 chance.

That is a very common way of assigning variables in Lua based on conditionals. It’s the same you’d do, for example, in Python with “foo = a if x else b”:
The first function, math.random(2), returns either 1 or 2. So, if it returns 1 the part math.random(2) == 1 is true and so you assign 100 to the variable ballDX. Otherwise, assign -100 to it.

In lua
result = condition and first or second
basically means the same as
if condition and first ~= nil and first ~= false then
result = first
else
result = second
end
So in your case
if math.random(2) == 1 then
ballDX = 100
else
ballDX = -100
end
in other words, there is a 50/50 chance for ballDX to become 100 or -100

For a better understanding, a look at lua documentation helps a lot :
https://www.lua.org/pil/3.3.html
You can read:
The operator or returns its first argument if it is not false; otherwise, it returns its second argument:
So if the random number is 1 it will return the first argument (100) of the "or" otherwise it will return the second argument (-100).

Related

What does a "for i, v" loop do?

I understand, "for i, v" loops for tables, i is the index, and v is the value, but what does this script do? I do not think this has anything to do with tables, but the only type of for table loops I know in ROBLOX script is the first one I mentioned; "for i, v" loops, which loop through tables.
randomVariable = 1
for i = 1, randomVariable do
(random script)
end
This is a numeric loop statement.
for controlValue = startValue, endValue, stepValue do
-- for body
end
It goes from startValue until it reaches endValue, after running body code, controlValue is increased by stepValue. If controlValue is higher or equals to endValue the loop stops. If stepValue is not provided, it equals to 1.
It's equivalent to this code:
local controlValue = startValue
if not stepValue then stepValue = 1 end -- if no stepValue it equals to 1
while controlValue < endValue do
-- for body
controlValue = controlValue + stepValue
end
There are a few different ways to loop in Lua.
while variable < number do
repeat stuff until variable == number
for key, value in pairs do
for index, value in ipairs do
for i = 1, number do
i = 1 is the initial condition.
It usually begins at one, then loops through items in a table.
So you can think of it as an index in that regard.
where the randomVariable you mentioned would be #tab
however, you could set that initial condition to be larger, then count down.
for i = #tab, 1, -1 do
the third, optional argument is called "step size"
and it's the amount that initial condition is changed, after completing each loop. it defaults to 1, so it's not needed, most of the time.
so to step through all the even numbers in a table it would be
for i = 2, #tab, 2 do
Further reading: https://www.tutorialspoint.com/lua/lua_loops.htm

What does this code mean (if v then return v end)?

So I have this piece of code and it is this:
do
local function index(n,m)
return n*(n+1)//2 + m
end
local binomtable = {}
function binom3(n,m)
if n<0 or m<0 or m>n then return 0 end
if n=0 or m=0 or m=n then return 1 end
local i = index(n,m)
local v = binomtable[i]
if v then return v end
v = binom3(n-1,m-1) + binom3(n-1,m)
binomtable[i] = v
return v
end
end
and I would like to know what
if v then return v end
means.
Thank you!
The short answer is that if v then return v end returns the value v if it is truthy, i.e., if it is neither false nor nil. Otherwise the function continues by calculating a value for v, storing that value in binomtable, and finally returning it. The more interesting question is, why is the function doing all of this?
In the posted code, binom3 is a recursive function. With the recursive calls v = binom3(n-1,m-1) + binom3(n-1,m) there will be a lot of duplication of effort, meaning a lot of wasted space and time. Consider:
binom3(4, 2)
--> binom3(3, 1) + binom3(3, 2)
--> binom3(2, 0) + binom3(2, 1) + binom3(2, 1) + binom3(2, 2)
--> 1 + binom3(1, 0) + binom3(1, 1) + binom3(1, 0) + binom3(1, 1) + 1
Note how in the second reduction there are two identical terms:
binom3(2, 1) + binom3(2, 1)
There is no reason to calculate the term binom3(2, 1) twice, and doing so means that the pair of terms:
binom3(1, 0) + binom3(1, 1)
also must be calculated twice, as seen in the third reduction. It would be smart to calculate binom3(2, 1) only once, and to save the result for later use in the larger calculation. When m and n are larger and the number of calculations explodes exponentially this becomes a very important issue for performance both in the amount of memory required and in the amount of time required.
The posted code is using memoization to improve performance. When a calculation is made, it is stored in the table binomtable. Before any calculation is made, binomtable is consulted. First, v is set to the value of binomtable[i]; if this value is any truthy value (any integer is a truthy in Lua), then that value is simply returned without the need for recursive calculation. Otherwise, if nil is returned (i.e., no value has yet been stored for the calculation), the function continues with a recursive calculation. After completing the calculation, the new value is stored in binomtable for use the next time it is needed. This strategy saves a lot of wasted computational effort, and can make a huge difference in the performance of such recursive algorithms.
For your specific question of what
if v then return v end
means, is that if v, a variable, is not nil or false it is to return the value of the v variable and stop executing that function.
--Similar
function myfunc(input)
local MyVar = "I am a string and am not nil!"
if MyVar then
return "hi"
else
return "hello"
end
print("I am not seen because I am unreachable code!")
end
if this function was called it would always return "hi" instead of "hello" because MyVar is true, because it has a value. Also the print function below that will never get called because it stops executing the function after a return is called.
Now for your codes case it is checking a table to see if it has an entry at a certain index and if it does it returns the value.

lua overload: possibilities?

My group is currently working with Lua,creating an android game. One thing we've run into is the appearant inability to create overload constructors.
I'm used to having an object set up with default values, that then get overloaded if need be.
ex:
apples()
{
taste="yum";
amount = 0;
}
apples(string taste, int num)
{
taste=taste;
amount=num;
}
However, with the inability to do that, we have these lare if/else sections for initialization that look like this
if velX ~= nil then
self.velX = velX
else
self.velX = 0
end
if velY ~= nil then
self.velY = velY
else
self.velY = 0
end
Is there a better way to set this up in Lua?
Instead of using if/else statements, you can initialize your variables with a condition providing the default value.
function apples(taste, num)
taste = taste or "yum"
amount = num or 0
-- ...
end
Lua's or operator evaluates and returns its first operand unless it is nil or false, otherwise it evaluates and returns its second operand. That leads to the above idiom for default values.

Behavior of load() when chunk function returns nil

From the Lua 5.1 documentation for load():
Loads a chunk using function func to get its pieces. Each call to func must return a string that concatenates with previous results. A return of an empty string, nil, or no value signals the end of the chunk.
From my testing, this is not actually true. Or, rather, the documentation is at a minimum misleading.
Consider this example script:
function make_loader(return_at)
local x = 0
return function()
x = x + 1
if x == return_at then return 'return true' end
return nil
end
end
x = 0
repeat
x = x + 1
until not load(make_loader(x))()
print(x)
The output is the number of successive calls to the function returned by make_loader() that returned nil before load() gives up and returns a function returning nothing.
One would expect the output here to be "1" if the documentation is to be taken at face value. However, the output is "3". This implies that the argument to load() is called until it returns nil three times before load() gives up.
On the other hand, if the chunk function returns a string immediately and then nil on subsequent calls, it only takes one nil to stop loading:
function make_loader()
local x = 0
return {
fn=function()
x = x + 1
if x == 1 then return 'return true' end
return nil
end,
get_x=function() return x end
}
end
loader = make_loader()
load(loader.fn)
print(loader.get_x())
This prints "2" as I would expect.
So my question is: is the documentation wrong? Is this behavior desirable for some reason? Is this simply a bug in load()? (It seems to appear intentional, but I cannot find any documentation explaining why.)
This is a bug in 5.1. It has been corrected in 5.2, but we failed to incorporate the correction in 5.1.
I get slightly different results from yours, but they are still not quite what the documentation implies:
function make_loader(return_at)
local x = 0
return function()
x = x + 1
print("make_loader", return_at, x)
if x == return_at then return 'return true' end
return nil
end
end
for i = 1, 4 do
load(make_loader(i))
end
This returns the following results:
make_loader 1 1
make_loader 1 2
make_loader 2 1
make_loader 2 2
make_loader 2 3
make_loader 3 1
make_loader 3 2
make_loader 4 1
make_loader 4 2
For 1 it's called two times because the first one was return true and the second one nil. For 2 it's called three times because the first one was nil, then return true, and then nil again. For all other values it's called two times: it seems like the very first nil is ignored and the function is called at least once more.
If that's indeed the case, the documentation needs to reflect that. I looked at the source code, but didn't see anything that could explain why the first returned nil is ignored (I also tested with empty string and no value with the same result).

Lua fails to evaluate math.abs(29.7 - 30) <= 0.3 [duplicate]

This question already has answers here:
What is a simple example of floating point/rounding error?
(9 answers)
Why is Lua arithmetic is not equal to itself? [duplicate]
(1 answer)
Closed 9 years ago.
Today morning I found a bug on my Lua Script, wich seem very weird. How can this evaluation fail this way? Examples can be tested in here
First example:
if( math.abs(29.7 - 30) <= 0.3 ) then
result = 1
else
result = 0
end
print("result = "..result )
-->> result = 0
Second example:
if( 0.3 <= 0.3 ) then
result = 1
else
result = 0
end
print("result = "..result )
-->> result = 1
Third example
if( math.abs(29.7-30) == 0.3 )then
print("Lua says: "..math.abs(29.7-30).." == 0.3")
else
print("Lua says: "..math.abs(29.7-30).." ~= 0.3")
end
-->> Lua says: 0.3 ~= 0.3 WHAT?
I am really confuse, and I would like to understand this to avoid similiar bugs in the future. Thanks
You are being hit by the fact that Lua uses (IEEE 754) 64-bit double-precision floating point numbers.
Look at the following examples
> print(0.3 == 0.3)
true
> print(0.3 <= 0.3)
true
> print(0.3 >= 0.3)
true
The actual value of 0.3 in memory is:
> print(string.format("%1.64f",math.abs(-0.3)))
0.2999999999999999888977697537484345957636833190917968750000000000
Now look at you example:
> print(math.abs(29.7-30) == 0.3)
false
> print(math.abs(29.7-30) >= 0.3)
true
> print(math.abs(29.7-30) <= 0.3)
false
The actual value of 29.7-30 is:
> print(string.format("%1.64f",29.7-30))
-0.3000000000000007105427357601001858711242675781250000000000000000
The actual value of math.abs(29.7-30) is:
> print(string.format("%1.64f", math.abs(29.7-30))
0.3000000000000007105427357601001858711242675781250000000000000000
And just for fun the value of math.abs(-0.3) is:
> print(string.format("%1.64f", math.abs(-0.3)))
0.2999999999999999888977697537484345957636833190917968750000000000
There are two solutions to you problem, the first is read What Every Computer Scientist Should Know About Floating-Point Arithmetic, and understand it :-). The second solution is to configure Lua to use another type for numbers, see Values and Types for hints.
Edit
I just thought of another way of "solving" the problem, but it is a bit of a hack, and not guarantied to always work. You can use fixed point numbers in lua by first converting the float to a string with a fixed precision.
In your case that would look something like:
a = string.format("%1.1f", math.abs(29.7 - 30))
print(a == "0.3")
or a bit more robust:
a = string.format("%1.1f", math.abs(29.7 - 30))
print(a == string.format("%1.1f", 0.3))
However you must make sure that you use a precision that is both adequate and the same for all you comparisons.
As we know, float point has a precision problem
Refer: http://lua-users.org/wiki/FloatingPoint
a = 1
if a < 1 then print("<1") end
Will never print "<1". Not unless you actually change a

Resources