for
proc f(size=1) =
if size == 1:
var
widFrame = 320
hiFrame = 200
else:
var
widFrame = 3200
hiFrame = 2000
echo (widFrame, hiFrame)
f()
I get
t_bug.nim(11, 11) Error: undeclared identifier: 'widFrame'
Why?
I know there is a solution
proc f(size=1) =
var
widFrame:int = 0
hiFrame:int = 0
if size == 1:
(widFrame, hiFrame) = (320, 200)
else:
(widFrame, hiFrame) = (3200, 2000)
echo (widFrame, hiFrame)
f()
but in fact widFrame and hiFrame should be read-only if the parameter size is given, what I expect is
proc f(size=1) =
if size == 1:
var
widFrame = 320
hiFrame = 200
else:
var
widFrame = 3200
hiFrame = 2000
echo (widFrame, hiFrame)
f()
which of cause failed with message t_bug.nim(11, 11) Error: undeclared identifier: 'widFrame'. What is the solution for this case?
Thanks
read-only -> using let
proc f(size=1) =
let (widFrame, hiFrame) =
if size == 1: (320, 200) else: (3200, 2000)
echo (widFrame, hiFrame)
f()
According to Nim manual:
https://nim-lang.org/docs/manual.html#statements-and-expressions-if-statement
In if statements new scopes begin immediately after the if/elif/else keywords and ends after the corresponding then block.
For example:
if true:
let foo = 1
# Error: undeclared identifier: 'foo'
echo foo
You can write shorter code by using if expression and tuple unpacking
https://nim-lang.org/docs/manual.html#statements-and-expressions-if-expression
https://nim-lang.org/docs/manual.html#statements-and-expressions-tuple-unpacking
proc f(size=1) =
let (widFrame, hiFrame) = if size == 1: (320, 200) else: (3200, 2000)
echo (widFrame, hiFrame)
f(1)
f(2)
This is similar to most languages, when you use a if statement, all variables declared within are local to the if branch and are invalid outside of it.
If size is known at compile time you can use when instead which doesn't create a new scope:
proc f(size: static int=1) =
when size == 1:
let
widFrame = 320
hiFrame = 200
else:
let
widFrame = 3200
hiFrame = 2000
echo (widFrame, hiFrame)
f()
Otherwise, use if-expression
proc f(size=1) =
let
widFrame = if size == 1: 320
else: 3200
hiFrame = if size == 1: 200
else: 2000
echo (widFrame, hiFrame)
f()
Note that I'm assuming this is a toy example, otherwise it might be better to pass a size + scaling factor.
thanks anyone. I am using python in which
def f(size=1):
if size == 1:
widFrame = 320
hiFrame = 200
else:
widFrame = 3200
hiFrame = 2000
print(widFrame, hiFrame)
f()
will says
320 200
so this is the difference between them
I am using python
In Python variables are allowed to exit the scope of the loop/conditional where they're defined. For example:
for i in range(5):
print(i)
print(2*i) # prints 8
In Nim these kind of things are not allowed, as others have already explained.