What does the indent change in this kind of code? - printing

Newbie here. I understand that for Python, indentation is extremely important. However, I'm having trouble understanding what the indent tells Python to do differently.
In this block of code,
smallest_till_now=0
for num in [-1,-2,5,4,-10,9]:
if num<smallest_till_now:
smallest_till_now=num
print(smallest_till_now,num)
I get
-1 -1
-2 -2
-2 5
-2 4
-10 -10
-10 9
But for this block of code:
smallest_till_now=0
for num in [-1,-2,5,4,-10,9]:
if num<smallest_till_now:
smallest_till_now=num
print(smallest_till_now,num)
I get this:
-1 -1
-2 -2
-10 -10
The only difference is the level of indent for the print(smallest_till_now,num) line.
Thank you in advance.

for num in [-1,-2,5,4,-10,9]:
if num<smallest_till_now:
smallest_till_now=num
print(smallest_till_now,num)
Here the print() statement is in the for loop block not in the if block ..so print is executed for every iteration of for loop irrespective of if statement is true or false
smallest_till_now=0
for num in [-1,-2,5,4,-10,9]:
if num<smallest_till_now:
smallest_till_now=num
print(smallest_till_now,num)
But here the print statement is in if block.. so it is printed whenever the if statement become true...

Related

Variable declaration that I don't understand in Lua

I was reading some Lua and doing a little course to use it with Löve 2D, in an example they give declare a variable this way, which I honestly do not understand:
ballDX = math.random(2) == 1 and 100 or -100
I've tried to google and read a bit but haven't found a place to specifically explain that. Looking at what it says I identify the obvious, BallDX is equal to a random number between 1 and 2, but from there I get quite confused, what does it mean that the random number is equal to 1 and 100 or -100?
This is a kinda interesting Lua concept
The operator and returns its first argument if it is false; otherwise, it returns its second argument.
The operator or returns its first argument if it is not false; otherwise, it returns its second argument
In this case math.random(2) == 1 and 100 or -100 behaves exactly like a ternary operator, it can translate to:
If math.random(2) equals to 1, set ballDX = 100, otherwise set ballDX = -100
For example, assume you had a variable called c, and you want to assign it a value only if a variable is above 10, with a ternary operator you would do this: c = a > 10 ? a : b
In Lua you would use c = a > 10 and a or b

How to round towards zero in lua

I have to round a value towards zero to know when it has gotten 1 larger than before
I have tried rounding normally but it doesn't work as I wanted.
local ghostwalkspeed = 0
function onTouched(hit)
if hit.Parent:FindFirstChild("Humanoid") then
hit.Parent.Humanoid.WalkSpeed = hit.Parent.Humanoid.WalkSpeed + hit.Parent.Humanoid.WalkSpeed/100
--!!!!!!
-- In the if statement below I have to
-- round "hit.Parent.Humanoid.WalkSpeed" towards zero
--!!!!!!
if hit.Parent.Humanoid.WalkSpeed > ghostwalkspeed then
ghostwalkspeed = hit.Parent.Humanoid.WalkSpeed
end
end
end
script.Parent.Touched:connect(onTouched)
Ghostwalkspeed is 0, walkspeed is 1. The ghost variable should not change to walkspeed until walkspeed is 2, so it should round from 1.9 to 1.
math.floor(1.9) or 1.9//1 will both evaluate to 1.
Lua Reference Manual 3.4.1. Arrithmetic Operators
Lua Reference Manual 6.7 Mathematical Functions: math.floor
https://en.wikipedia.org/wiki/Floor_and_ceiling_functions
Please read manuals!

How to tell if a Lua line number is a valid execution point (from C/C++)?

How Can I tell if line number x in a Lua script will respond to the Lua line hook?
Example:
1 first = 1
2
3 function test ( data )
4 if first == 0 then
5 print ("\r\n")
6 end
7 print(data)
8 --[[
9 first = 0
10 ]]
11 end
12
13 test()
14
Line 2,6,8,9,10,12 and 14 does not call a line hook. After I have loaded and executed the script, can I some how, from C/C++, get a table of the executable line numbers?
lua_getinfo can return a table of valid lines if you include L in what.
Some code sample:
local exec_lines = {}
local function exec_line_counter(event, line)
table.insert(exec_lines, line)$
end
local function count_exec_lines(lua_file)
local external_chunk = loadfile(lua_file)
debug.sethook(exec_line_counter, "l")
external_chunk()
debug.sethook()
-- Removing `debug.sethook()` lines:
table.remove(exec_lines, 1)
table.remove(exec_lines, #exec_lines)
end
count_exec_lines("test.lua")
Output of:
table.sort(exec_lines)
for i, num in ipairs(exec_lines) do
print(num)
end
is
1
3
4
7
11
11 <--- not sure why this duplicates. Lack of return? Or because following tailcall?
13
NOTE: it would log only lines being parsed. In Your test case, it does not cover 5th and 6th line, because first not being 0.
Another way of doing this and solving noted case - just simply parsing Lua source: counting and skipping lines which consists only of Lua comments:
--lines
--[[ blocks ]]
EDIT: ah, shoot, edited Your question of doing this with C/C++. Hooking functions can be done with plain C API too. Might make an example if You didn't get a basic idea from an my answer already made :)

"Attempt to index local..." Why am I getting this error?

I'm new to Lua and trying to get things sorted in my head. I tried this code:
function newCarousel(images)
local slideToImage = function()
print("ah!")
end
end
local testSlide = newCarousel(myImages)
testSlide.slideToImage()
Which gave me this error:
Attempt to index local "testSlide" (a nil value)...
Why is this?
Because newCarousel returns nothing, so testSlide is nil, so when you try to index it (testSlide.slideToImage is exactly equivalent to testSlide["slideToImage"]) you get an error.
I would recommend reading Programming in Lua. You may be able to work out the language's syntax, semantics, and idioms by trial and error, but it'll take you a lot longer.
If you want to be able to do testSlide.slideToImage() you have to modify newCarousel so that it returns a table with a function inside it. The simplest implementation is the following:
function newCarousel(images)
local t = {}
t.slideToImage = function()
print("ah!")
end
return t
end
You can even build t and return it on a single step; the following code is equivalent to the one above:
function newCarousel(images)
return {
slideToImage = function()
print("ah!")
end
}
end
The code you've got now, as Mud stated, doesn't return anything. (This is not Scheme or Ruby or the like where the last expression is the return value.) Further, you seem to be thinking that newCarousel is an object. It isn't. It's a function. When you've finished calling newCarousel it's over. It's done its work, whatever that may be (which in your case is creating a local variable that is promptly dropped and returning nil).
Correct code for this would look more like:
function newCarousel(images)
return function()
print("ah!")
end
end
local testSlide = newCarousel(myImages)
testSlide()
Here I now have newCarousel creating an (anonymous) function and immediately returning it. This anonymous function is bound to testSlide so I can invoke it any time I like for as long as testSlide remains in scope.
It's instructive to look at the generated code when playing with Lua. First let's look at what luac churns out for your code:
main <junk.lua:0,0> (8 instructions, 32 bytes at 0xeb6540)
0+ params, 2 slots, 0 upvalues, 1 local, 3 constants, 1 function
1 [5] CLOSURE 0 0 ; 0xeb6720
2 [1] SETGLOBAL 0 -1 ; newCarousel
3 [7] GETGLOBAL 0 -1 ; newCarousel
4 [7] GETGLOBAL 1 -2 ; myImages
5 [7] CALL 0 2 2
6 [8] GETTABLE 1 0 -3 ; "slideToImage"
7 [8] CALL 1 1 1
8 [8] RETURN 0 1
function <junk.lua:1,5> (2 instructions, 8 bytes at 0xeb6720)
1 param, 2 slots, 0 upvalues, 2 locals, 0 constants, 1 function
1 [4] CLOSURE 1 0 ; 0xeb6980
2 [5] RETURN 0 1
function <junk.lua:2,4> (4 instructions, 16 bytes at 0xeb6980)
0 params, 2 slots, 0 upvalues, 0 locals, 2 constants, 0 functions
1 [3] GETGLOBAL 0 -1 ; print
2 [3] LOADK 1 -2 ; "ah!"
3 [3] CALL 0 2 1
4 [4] RETURN 0 1
In your code the mainline creates a closure, binds it to the name newCarousel, gets that value, gets the value of myImages and does a call. This corresponds to local testSlide = newCarousel(myImages). Next it gets the slideToImage value from the local table (testSlide). The problem here is that testSlide isn't a table, it's nil. This is where your error message is coming from. This isn't the only error, mind you, but it's the first one the runtime sees and is what's making everything choke. If you'd returned an actual function from newCarousel you'd get a different error. If, for example, I'd added the line return slideToImage to the newCarousel function, the error message would have been "attempt to index local 'testSlide' (a function value)".

Lua value not changing?

I use very simple Lua scripting in an online game called ROBLOX. My problem is that values in my scripts aren't changing! Example:
num = 0
while true do
num = num + 1
print(num)
wait(1)
end
That should count up starting on 0, but the number won't change. Could this be from the ROBLOX website? I can't figure out what else it might be.
What happens with
local num = 0
while true do
num = num + 1
print(num)
wait(1)
end
?
Maybe some other part of the system is changing the global num.
I just put your code in the Lua demo and it works fine if you remove the wait() function call. I'm assuming you defined this function somewhere?
There is nothing wrong with the code. You must be running it wrong. Also, wait is a function defined in the Roblox API. It is legit.
There is no error in your code. If you are using ROBLOX, then I'm not sure how you're running it wrong as it is a fairly simple interface. I'll try it in ROBLOX and see if it errors for me.
To the people who were wondering about wait(): it's a ROBLOX-specific global function, that pauses the current task the amount of seconds in the parentheses.
Try this:
local num = 0
while true do
num = num + 1
print(num)
print(type(num))
wait(1)
end

Resources