lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2011/4/4  <jose.camacho@ifm.com>:
> The problem is in the "..." string. The loadstring () operator tries to load
> it as a string and it fails, because "..." it is *not* a valid string.

It is not valid because calling loadfile/loadstring is not the correct
method to load a Lua module.

> Instead of that, what I now load the module in a lua string and do a
> substitution: instead of "...", the string "module_name" (which the
> corresponding module name, "defs" in my previous example ) is used.
>
> It is also the correct approach, because in this way, lua states can match
> the module loaded with loadstring () with a package in the state.
>
> Therefore, it goes:
> TCP client request a module from Server
> Server sends the module as string
> Client substitues the string '...' by 'module name'
> Client calls loadstring (module_content).
>
> All lua scripts can now use the module got from the far-end

That substitution is not necessary. To load a module from the network,
you simply have to write a searcher function that takes the module
name as parameter, and puts the module main chunk in package.preload.
Then you can call require, and require will pass the module its own
name so that ... is properly defined.

To write a searcher functions, you can look at examples from the wiki
[1][2][3]. In your case, it would look like:

-- this assumes a get_source_from_server function that you have to define
local function my_searcher(modulename)
  -- Find source
  local src = get_source_from_server(modulename)
  if not src then
    -- Return a partial message that require will aggregate
    return "\n\tno module '"..modulename.."' on the server"
  else
    -- Compile and return the module
    return assert(loadstring(src))
  end
end

table.insert(package.loaders, my_searcher)


[1] http://lua-users.org/wiki/LuaModulesLoader
[2] http://lua-users.org/wiki/BinaryModulesLoader
[3] http://lua-users.org/wiki/HashedModulesLoader