Lua Sockets Module cpath - lua

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.

Related

Lua require error if script is called "table.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.)

Lua: relative import fails from different working directory

I'm trying to repackage into a Docker container some Lua library that is made of the main module and some helper modules. The helper modules are kept inside a subfolder of the library so that imports from the main file are done as
require 'helpers/SomeHelper'
The problem is: because of the way I want the Docker container to work, it would be extremely helpful if I can invoke this library from a different working folder. That is, my call to the main program would be something like
th /app/main.lua
regardless of the actual working directory I'm standing. Unfortunately, relative imports seem to fail when the working directory is different from the directory where the main file is located.
Is there any way I can configure LUA_PATH or any other mechanism to make these imports work correctly? Note that changing the code of the library itself would be a poor solution, as it wasn't developed by me and I would like to be able to update it to newer versions easily.
If you don't care about the working directory, you can just load lfs / LuaFileSytem and use lfs.chdir( src_dir ) to change to the source directory (potentially saving the current working directory with lfs.currentdir( ) first.)
You can also extend the search path of Lua so that it will search those extra directories. The search is driven by package.searchpath. To add a directory /foo/bar/ to the search in a way that supports all normally supported library layouts, add
/foo/bar/?.lua;/foo/bar/?/init.lua to package.path
/foo/bar/?.so (or .dylib or .dll on other OSen) to package.cpath
You can use several ways to extend the path.
One option that works well is to set the LUA_PATH / LUA_CPATH environment variables. (A ;; sequence in one of them will expand to the full default path.) This can be done from .profile or other setup scripts via an earlier export LUA_PATH="..." or (if started from a wrapper script) inline by setting variables just for that call LUA_PATH="..." lua /foo/bar.lua. (Note that if you export this variable in too broad a scope, other Lua scripts will also get their path extended and may find potentially incompatible Lua libraries.)
(You can also manually modify package.(c)path from LUA_INIT. That way, you won't be able to independently disable LUA_INIT or LUA_PATH, but you can use all of Lua to generate the path dynamically.)
A third option (this may be best in your specific case) is to put the extension of package.path at the top of your main script, as in
do
local dir = (arg[0]:match "^(.*)/$")
if dir then -- else cwd is . which works by default
package.path = dir.."/?.lua;"..dir.."/?/init.lua;"..package.path
package.cpath = dir.."/?.so;"..package.cpath
end
end
-- rest of your program goes here
When running a script with the Lua interpreter, arg[0] is the script. So this extends the path to include the program's directory no matter where it is located, and it will only affect the search path of this particular script / program.
You should not forget about that not all modules are loaded from FS directly.
E.g. to improve perfomance it is possible read/compile file to memory and then
use preload table to provide way to load module from memory.
Basic example
--- preload code. It can be done by host application.
local FooUtils = function()
return {
print = function(...)
print("foo", ...)
end
}
end
local Foo = function()
local Utils = require "foo.utils"
return {
foo = function()
Utils.print"hello"
end
}
end
package.preload['foo.utils'] = FooUtils
package.preload['foo'] = Foo
--- main application
require "foo".foo()
In this example assume that FooUtils and Foo just example of compiled modules.
E.g. it can be like FooUtils = loadstring('path/to/utils.lua) and it can be done
even in separate Lua state and then used in any other.
It is important to remember that Foo module have no idea about how host application does lookup of foo.utils.
So there no standart way to provide original file path or relevant paths.
So if you write some module wich relays on relative paths then this module
may be not working in some environments.
So I just suggest use full namespace like require 'foo.utils' instead of require 'utils'

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.

Embedding LuaJIT module into C application

In my application, I have all the Lua libraries exposed from the C backend. Now, I have a need to load a Lua module. The method for this seems to be :
lua_getglobal(L, "require");
lua_pushstring(L, libname);
lua_pcall(L, 1, 0, 0);
which will search the package.path to find <libname>.lua and load it.
Is it possible to build-in the Lua module into the C application (so that the module becomes part of the C application) ? so that I don't have to separately package the Lua module. Somehow I am not able to find any references or examples of this! :(
p.s. I am using LuaJIT-2.0.2, and the library in question is SciLua/Time (uses ffi)
Yes.
luajit -b Module.lua Module_bc.c
will compile a module to bytecode and output a C array initializer containing that bytecode.
If you build with shared libraries enabled and export this array from the main executable, require will find it (and will not need to look for Module.lua.)
To test that it is working, set package.path = "" before requireing the module. If it still works, you know the preload is working and it is not just using the Module.lua file from the current directory.
http://luajit.org/running.html
Other things to keep in mind:
If the module depends on an external file (using io.open), that file still needs to be present. For example some ffi modules try to open a C header file, to pass to ffi.cdef
You need to keep Module_bc.c in sync with Module.lua, e.g. with a Makefile recipe, or you will see some confusing bugs!

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