Lua beginner - <eof> error when loading/saving array from a text file

Viewed 23

I am using an application (SIMION) that uses Lua as a scripting language, but I am very new to Lua. The SIMION website has lots of help pages and I am stuck on the first code fragment on this page: Code fragment (Method 1 of Loading/Saving an array from a text file).

The code goes as:

-- test.dat:
return {
  3, 1, 4,
  1, 5, 9
}

-- test.lua:
local array = dofile("test.dat")
-- print contents
for i,v in ipairs(array) do
   print(i,v)
end

Now I have a couple of issues with this code: firstly, I get an error when I run this script:

C:\Program Files\Lua\lua54.exe: c:\Users\RD\Documents\Lua-code\array.lua:8: <eof> expected near 'local'

As I am using VScode with the Lue extension it suggests the following fix to the code:

-- test.dat:
do return {
   3, 1, 4,
   1, 5, 9
} end

With this 'fix' I now get no output (and no errors), so not as I expected from the help pages I referenced earlier in this post.

Could somebody help me with this please? Given that I want to use Lua and SIMION together, I would really appreciate some guidance/pointers on what's going wrong.

1 Answers

Syntax Error

return statements must be the last statement in a block/chunk as per the Lua grammar. A return statement followed by further statements thus is a syntax error.

On the Suggested "Fix"

The fix your extension suggests is one that turns everything after the return into dead code by wrapping the return in a do-end block where it becomes the last statement of the block again. A similar hack would be an if true then-end wrapping (as is done in other languages lacking an equivalent of the do-end where compilers don't allow the return to be followed by dead code either).

The purpose of such a hack always is to disable subsequent portions of code to enable quick and dirty testing. This is similar to commenting out everything after the return, which would have the same effect (disabling the following code).

Actual Fix

The comments hint that these snippets are supposed to be placed in two different files (especially as test.lua executes test.dat), test.dat which returns a Lua table when run (which is presumably why it is called "dat" for "data", even though that's probably an unsuitable file extension here).

Thus, place the two snippets in two different files:

test.dat:
return {
  3, 1, 4,
  1, 5, 9
}
test.lua:
local array = dofile("test.dat")
-- print contents
for i,v in ipairs(array) do
   print(i,v)
end
Related