Lua require error if script is called "table.lua"? - lua

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.

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.)

Related

Lua - including file doesnt work, how can I fix it?

I have a problem with lua include (dofile, loadfile, require). What I want to do is including file to my main lua file.
Main file - stala_2enb_lua.lua
File to include - zmienne_2enb_modyfikacja
I want to have my main file constant and make changes only in second file, where I want to have variables.
Main file
File to include
I tried all ways like on the screen, but I have no output. It behaves like this all including doesnt matter. There is no error and the variables are not included. How can I make it correctly?
UPDATE
I've managed to load a little bit using dofile, but there is an error which I can't understand. I've found a solution, but i can't understand it properly --> devdocs.io/nginx_lua_module --> ctrf +f = Lua Coroutine Yielding/Resuming
Error after loading function using dofile ("/home/epcsim/WTS_2001_WK05/zmienne_2enb_lua.lua")
Thanks in advance for the help!

in lua (love2D), i want to import a library in a subfolder, the file in there will not find the next module it requires

So in lua, i want to import a module.
I want to have my "polygon" lib in a subfolder, so i reference it like this
local polygon = require('polygon.polygon')
however, it needs another module called 'delaunay', it cannot find it as it checks the main folder
Is there anyway short of editing my library, to get this to work? (some kind of ability to add search paths?)
Thanks
To know where to look for modules, Lua's require uses the variables package.path (.lua) and package.cpath (.so/.dll). You can change them in your program to look in the directory you have it in. For consistency's sake, you can look at their contents to know which OS-specific separator to use. For example:
local sep = package.path:find("\\") and "\\" or "/"
package.path = package.path .. ";." .. sep .. "polygon" .. sep .. "?.lua"
This would include ./polygon/?.lua into the search path, and a call to require "delaunay" would therefore have the require function look for ./polygon/delaunay.lua in addition to existing paths. Bear in mind that in require strings, . denotes a separator as far as file searching is concerned, so calling require "polygon.delaunay" in this scenario will mean searching for ./polygon/polygon/delaunay.lua.
From what I understand of your question, changing the package.path variable to include the path to where your delaunay library is stored would solve your issue, although to give a specific solution more information about your project and directory structure is required.
All what loaded into package.loaded can be load with require() because require() looks first in package.loaded...
-- Lua 5.3 ( lua -i )
> package.loaded.code=load(code.dump)()
> test=require('code')
> test
function: 0x565cb820
So you can use load() or loadfile('/path/to/your_code.lua') to do this. Another nice feature of this method is to load dumped code...
> package.loaded.shell=loadfile('shell.bin')
> shell=require('shell')
> shell('cat shell.bin')
uaS�
�
xV(w#F#�d�#��F�#G���d#��F�#G���d#&�typestringoexecute
/bin/bash>
In any way, it appears that you will have to deal with the subfolders explicitly.
As in, either the module polygon will have to import delaunay as polygon.delaunay.
Or module names will have to be appended to package.path so that lua could search through subfolders for filenames:
package.path=package.path..";./polygon/?.lua"
More info is here.
It is pointed out in comments, you'd probably want to ensure that path concatenation happens only once.
Also, one should be wary of name shadowing.
Finally, while we are at stirring up the past, a pretty nifty trick to solve the issue was proposed here five years before the question.

How to call a function from a lua file of a c++/lua project on interactive terminal?

I'm reading some source codes of a project, which is a combination of c++ and lua, they are interwined through luabind.
There is a la.lua file, in which there is a function exec(arg). The lua file also uses functions/variables from other lua file, so it has statements as below in the beginning
module(..., package.seeall);
print("Loading "..debug.getinfo(1).source.."...")
require "client_config"
now I want to run la.exec() from interactive terminal(on linux), but I get errors like
attempt to index global 'lg' (a nil value)
if I want to import la.lua, I get
require "la"
Loading #./la.lua...
./la.lua:68: attempt to index global 'ld' (a nil value)
stack traceback:
./lg.lua:68: in main chunk
[C]: in function 'require'
stdin:1: in main chunk
[C]: ?
what can I do?
Well, what could be going wrong?
(Really general guesswork following, there's not much information in what you provided…)
One option is that you're missing dependencies because the files don't properly require all the things they depend on. (If A depends on & requires B and then C, and C depends on B but doesn't require it because it's implicitly loaded by A, directly loading C will fail.) So if you throw some hours at tracking down & fixing dependencies, things might suddenly work.
(However, depending on how the modules are written this may be impossible without a lot of restructuring. As an example, unless you set package.loaded["foo"] to foo's module table in foo before loading submdules, those submodules cannot require"foo". (Luckily, module does that, in newer code without module that's often forgotten – and then you'll get an endless loop (until the stack overflows) of foo loading other modules which load foo which loads other modules which …) Further, while "fixing" things so they load in the interpreter you might accidentally break the load order used by the program/library under normal operation which you won't notice until you try to run that one normally again. So it may simply cost too much time to fix dependencies. You might still be able to track down enough to construct a long lua -lfoo-lbar… one-off dependency list which might get things to run, but don't depend on it.)
Another option is that there are missing parts provided by C(++) modules. If these are written in the style of a Lua library (i.e. they have luaopen_FOO), they might load in the interpreter. (IIRC that's unlikely for C++ because it expects the main program to be C++-aware but lua is (usually? always?) plain C.) It's also possible that these modules don't work that way and need to be loaded in some other way. Yet another possibility might be that the main program pre-defines things in the Lua state(s) that it creates, which means that there is no module that you could load to get those things.
While there are some more variations on the above, these should be all of the general categories. If you suspect that your problem is the first one (merely missing dependency information), maybe throw some more time at this as you have a pretty good chance of getting it to work. If you suspect it's one of the latter two, there's a very high chance that you won't get it to work (at least not directly).
You might be able to side-step that problem by patching the program to open up a REPL and then do whatever it is you want to do from there. (The simplest way to do that is to call debug.debug(). It's really limited (no multiline, no implicit return, crappy error information), but if you need/want something better, something that behaves very much like the normal Lua REPL can be written in ~30 lines or so of Lua.)

Lua Sockets Module cpath

I'm trying to use the sockets module in a script and I keep encountering a issue where the script is unable to find socket.core. Is there anyway for me to point to exactly where the core.dll is? I've tried using cpath and I can never seem to get it to work. I just want to be able to say "C:/folder/folder/folder/core.dll"
package.cpath = 'F:/Folder/Foldertwo/Game/agame/Beta/Scripts/libs/socket/?.dll;' .. package.cpath
#EgorSkriptunoff is correct in his comment: socket.lua (which is a lua module) loads socket.core (which is a dynamic library), so you won't be able to load it from folder/core.dll as the default searcher will be looking for socket/core.dll.
If you really want to load it from folder/core.dll, you may try to load it yourself and assign the returned value to package.preload['socket.core']. This way when socket.lua loads the module, it will get the value to return from package.preload key without loading the module.

Lua: require fails to find submodule, but searchpath succeeds?

usually when I have a question about something remotely software related I find that someone else has already asked the very same thing, and gotten good answers that works for me too.
This time, though, I've failed to find an answer to my predicament.
Here we go:
I'm currently trying to move up my Lua-programming a notch or three and want to use modules. So, I've got a structure like this:
main.lua
foo/bar.lua
Now, in main.lua I do
require("foo.bar")
which fails,
main.lua:1 module 'foo.bar' not found:
no field package.preload['foo.bar']
no file 'foo.bar.lua'
no file 'foo.bar.lua'
no file 'foo.lua'
Ok, something might be wrong with my package.path so I use package.searchpath("foo.bar", package.path) to see what I', doing wrong.
The problem is that package.searchpath resolves foo.bar to foo/bar.lua which is exactly right.
As I've understood it, package.searchpath tries to find the module in the same way as require, but there seems to be som glitch in my case.
What strikes me as odd is the repetition of the no file 'foo.bar.lua' in the error output
Have I misunderstood the use of require?
I'm using LuaJIT-2.0.0 to run my chunks
Update:
I'm using LuaJIT-2.0.0 to run my chunks <- This was the reason for my problem, stock Lua-5.2.2 behaves as expected
package.path = debug.getinfo(1,"S").source:match[[^#?(.*[\/])[^\/]-$]] .."?.lua;".. package.path
require("foo.bar")
This line causes require to look in the same directory as the
current file when asked to load other files. If you want it to instead
search a directory relative to the current directory, insert the
relative path between " and ?.lua
Here is part of require description:
[...] Otherwise require searches for a Lua loader using the path stored in
package.path. If that also fails, it searches for a C loader using the
path stored in package.cpath. If that also fails, it tries an
all-in-one loader (see package.loaders).
Default path for package.path is always the .exe that executes specified script.

Resources