1

I am using the C Fuzzy API and I want to load function module contained in a file lets say mycalculator.lua. This seem to run fine however when I later try to run another file A.lua that requires 'mycalculator' it does not work unless the mycalculator.lua file is available on the file system to reload. I am trying to just load it into the system and then have it available without having the mycalculator.lua in the file system. It there any way to have lua system keep the definition without loading it again? Basically I convert the mycalculator.lua into a string and then run it. I don't want to put mycalculator.lua file into the file system, I just want to hand it over as a string and then be able to require it in the next string I pass to the stack Thanks

Doug Currie
  • 40,708
  • 1
  • 95
  • 119
Androider
  • 21,125
  • 36
  • 99
  • 158
  • What *do* you have a place to put that string on? Strings don't exist magically on a file system, they always require some kind of storage. How do you plan to execute A.lua? – kikito Dec 22 '11 at 08:35

1 Answers1

2

There is a difference between simply executing a Lua script and loading a Lua module. If you wish to load a Lua module, then you must actually load a Lua module exactly as a script would: by calling require.

Since you appear to be new to Lua, I should probably explain this. You've probably seen code like this in Lua scripts:

require 'mycalculator'

That is not some special statement to Lua. That is a function call. It is just some syntactic sugar for:

require('mycalculator')

Functions in Lua can be called with NAME VALUE syntax instead of NAME(...) syntax, but it only allows you to send one parameter. And the parameter must be a literal (or table constructor).

In order to call the Lua require function from C, you must use the Lua stack. You must fetch the function from the global table by using lua_getfield(L, LUA_GLOBALSINDEX, "require"); Then, you push a string onto the stack containing the name of the module to load. Then, you use lua_pcall or whatever Lua function calling function to call it.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • Ok. Well I am interested in loading/requiring the module and passing this requirement in as a string. I want to pass a string that contains the content of the module that is required so that lua never goes to the file system for that module. Can this be done? – Androider Dec 22 '11 at 04:33
  • So in requiring loading I don't want lua to check the file system but instead I want to pass this module as a string. – Androider Dec 22 '11 at 04:35
  • So what I am asking is I don't want to use something like the following: path = "./path/to/a/file.lua" – Androider Dec 22 '11 at 04:40
  • Instead, I want to provide the file contents to lua. – Androider Dec 22 '11 at 04:40
  • I have reposted in terms of LUA Java and loading a string: http://stackoverflow.com/questions/8599597/how-do-i-load-lua-file-as-a-string – Androider Dec 22 '11 at 04:59