Search code examples
luaload

What does 'load' do in Lua?


I was Trying to sove my problem in understanding load function in Lua Scripts but there was not any Examples or guides for this command . it tells in his own Lua Website https://www.lua.org/manual/5.2/manual.html#pdf-load this :

load (ld [, source [, mode [, env]]])

can someone describe it to me please ?


Solution

  • load takes a chunk, compiles it, and returns as a function that can be called to execute the chunk. For example, the following will create a function that will add two numbers together:

    local func, err = load("return function(a,b) return a+b end")
    if func then
      local ok, add = pcall(func)
      if ok then
        print(add(2,3))
      else
        print("Execution error:", add)
      end
    else
      print("Compilation error:", err)
    end
    

    This should print 5.