I suspect that interpreter reads that code as:

local message = 'hello world',print('my message:', message)

Which means message isn’t actually assigned until after the print. (The print is evaluated before the assignment – otherwise how could you grab the result of a function?)

local message = 'hello world',print('my message:', message)
print('my real message:', message)
my message:	nil
my real message:	hello world

But, yeah, also right that it’ll fail anyway in a REPL.

More

In the REPL I believe each line is executed a separate chunk, so the local scope only lasts until the end of the line (or multiline).

So this would work:

Lua 5.4.7  Copyright (C) 1994-2024 Lua.org, PUC-Rio
> local message = 'hello world'; print('my message:', message)
my message:	hello world

And also this:

Lua 5.4.7  Copyright (C) 1994-2024 Lua.org, PUC-Rio
> do
>> local message = 'hello world'
>> print('my message:', message)
>> end
my message:	hello world

etc.

4 Likes