lua-users home
lua-l archive

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

On Friday 25 June 2004 12:22, Boguslaw Brandys wrote:
> So, rather then include link to another script in script itself - You said
> I must rather load script in C using lua_loadfile and assign to variable.
> This is what I can't understand.
> Also this common script will contain a lot of shared functions (for
> example to draw report elements like tables,comments - particulary I want
> to generate reports using Lua to build report preview from simple chunks
> and data returned from SQL database).Could You give me an example how to
> load common script from buffer to Lua global variable available to ANY
> script loaded from remote SQL database after that ?

Are you creating a new lua_State for each script you load from the database? 
If so, the simplest solution will be to bytecode-compile your common code 
using luac, and then either just load it using dofile (the performance impact 
of actually loading from a file repeatedly should be negligible thanks to the 
filesystem cache), or load in the compiled script from C and use 

A better approach is likely to be to reuse the same lua_State for each script. 
Then you can load your common functions at the start and they will always be 
available. If you need to avoid the scripts interfering with each other by 
polluting the global table, you can use 'sandboxing'. There are subtleties 
involved with doing that competely and securely, but the basic pattern is 
quite simple. I'll show it in Lua, but it's easy to code the same thing in C.

-- 'code' is a string containing the source code for your script.
-- The common code is already loaded using dofile or similar.
function sandbox(code)
    -- Load the code
    local chunk = assert(loadstring(code))

    -- Create an empty environment for it
    local env = {}

    -- Copy globals into the new environment as needed
    local mt = {
        -- Could just use __index = _G here, but this is faster:
        __index = function(t, k)
            local v = _G[k]
            t[k] = v
            return v

    -- Set the environment of the loaded chunk
    setfenv(chunk, setmetatable(env, mt))

    -- And execute it

-- Jamie Webb