SZMER SZMER - 1 year ago 192
JSON Question

LUA load JSON configuration from file

I'm trying to move old LUA method which was loading some JSON content from file into global variable into "class". But I get following errors all the time:

attempt to call field 'decode' (a nil value)
attempt to index global 'cjson' (a nil value)

I don't know lua well but i tried almost all combinations without result so can you explain why this errors occurs?

Current implementation of module looks like:

Config = {}
Config.__index = Config

function Config.create(config_filename)
local cjson = require("cjson")
local config = {}

local f =, "r")
local content = f:read("*a")
config = cjson.decode(content)

return config

return Config

As final result I want to execute something like this from other file:

local config_class = require("config")
local config = config_class.create("/path/to/file.json")


Answer Source

As the error message tells you cjson and decode are nil values which cannot be indexed or called.

require will load some file and run the contained code and pass the return value through. If you run a Lua script it behaves like a function which returns nil by default. So unless you specify what the script returns require will return nil.

I don't know what is inside your cjson file that you require but it obviously does not return the wanted json implementation but nil.

So the code in cjson should return a Lua table with a function stored under key "decode".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download