Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

module - Is it possible to require() a script that is loaded using luaL_loadstring()?

I'm a beginner in Lua.

I wonder if it is possible to use require('filename') to require a script that is loaded using luaL_loadstring().

Since luaL_loadstring(lua_State *L, const char *s) doesn't specify any filename, I don't know how to use require() to load this script from other script.

Does require() only works with actual .lua files?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well, take a peek into the documentation for require(), and you will see it's very flexible.

The relevant parts are:

  1. package.loaded[modname]. Just set it with the module name you want. Be sure to set it before you require it though.
  2. package.searchers and the default entries therein. This is only relevant if the module is not registered as loaded as noted above.

In more detail:

If you want to set up a package for require to find it, you have two choices: 1. Set it up as fully loaded by adding it to package.loaded, or 2. make sure it's found by one of the package.searchers-entries.
Any competent lua modules tutorial will tell you how to structure the module itself easily, the docs give you the mechanics of why too.
The registry, which contains an entry for the global environment, can be accessed from native code, so you can do it from there if you so desire.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...