1
votes

Trying to replicate this simple Lua example (using the improved code in the second post), I encountered the following strange issue:

I copied the code verbatim, but happened to call the first file "table.lua" (instead of "funcs.lua"). The second file was called "main.lua" as in the example.

In my case, whatever I tried, I invariably got the popular error message "attempt to call field 'myfunc' (a nil value)" (as if the require statement had been ignored; but path etc. were all in order).

After two hours of trying and hunting for info, I more or less on a hunch renamed the first file from "table.lua" to "tabble.lua", and then everything promptly worked as expected. Renaming to e.g. "tables.lua" will also work.

Being very new to Lua, I'd still like to understand what exactly went wrong. Initially I thought the reason might be that "table" is a reserved Lua word, but all references I checked do not list it as such.

So what is going on here?

I am using LuaForWindows v5.1.4-46 with the included SciTE editor/IDE (v.1.75).

Thanks for all hints.

1
It will be easier to help if you give the code you’re using in your own post, instead of through a link.Azure Heights

1 Answers

3
votes

The standard libraries math, io, string, …, and table are pre-defined (and pre-loaded) in the Lua interpreter. Because require caches modules by name, saying require "table" will return the standard table library instead of loading your own table module from a file.

A good way to solve the problem is to create a folder and put your library files in there. If the folder is called mylib, then require "mylib.table" will work and load the file.

Alternatively, if you just need to load the file once and do not need the features of require (searching the file in a number of directories, caching loaded libraries), you can use loadfile: Change require "table" to loadfile "./table.lua" () (where ./table.lua should be the full (relative is fine) path to the file.)