简体   繁体   中英

attempt to compare nil with number stack traceback?

I'm playing with Lua following this link: https://www.lua.org/pil/4.2.html and get confused about a point.

Lua 5.2.4  Copyright (C) 1994-2015 Lua.org, PUC-Rio
> x=10
> local i=1
> while i<=x do
>>  local x = i*2
>>  print(x)
>>  i=i+1
>> end
stdin:1: attempt to compare nil with number
stack traceback:
    stdin:1: in main chunk
    [C]: in ?

I guess this error message indicates that something is wrong with the expression while i<=x . Any comments are greatly appreciated. EDIT: I just realize that it's probably because it does not work in a terminal.

It did not work out in an interactive terminal. Because local i=1 is understood by terminal as a chunk by itself once you hit enter. That is why the "attempt to compare nil with number" error; because i is not defined, ie, nil in this case. To correct it, put the first two lines and the while loop inside of a do chuck as the following.

> do
>>  x = 10
>>  local i=1
>>  while i<=x do
>>    local x = i*2
>>    print(x)
>>    i = i+1
>>  end
>> end
2
4
6
8
10
12
14
16
18
20
> 

Actually the problem is in local i=1 try

> local i = 1
> print(i)

The problem is that when running the console, it seems that the line is a chunk and the variable is local inside that chunk. you can fix that by using a global variable or you can do this

> local i = 1 do
>> print(i)
>> end

Which results in chunk structure like this [local i [print(i)]] therefore i can be accessed. Note also that local x = i*2 is valid since it is inside the while - do chunk.

Your code would also work correctly, if it was inside a Lua file.

I could reproduce the problem in Lua 5.3.4 as well.

If you read on in the Lua docs, chapter 4.2 – Local Variables and Blocks , you'll get to the sentence

Beware that this example will not work as expected if you enter it in interactive mode. The second line, local i = 1, is a complete chunk by itself.

This addresses exactly the issue in question. So it seems that the Lua interpreter has limited support for an outmost chunk (that is clearly present in a Lua file). But this behaviour seems to me acceptable and understandable in view of the compactness of language and interpreter.

So, when in interactive mode,

either leave out the local before variable i to make it work:

Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
Lua>x=10
Lua>i=1
Lua>while i<=x do
...>local x=i*2
...>print(x)
...>i=i+1
...>end

or start enclose the whole by a block:

Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio
Lua>do
...>local x=10
...>local i=1
...>while i<=x do
...>local x=i*2
...>print(x)
...>i=i+1
...>end
...>end

Both options will produce to the regular (and expected) output:

2
4
6
8
10
12
14
16
18
20

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM