4

I'm trying to encode/decode JSON in Lua using CJSON. I downloaded lua-cjson using Luarocks (http://www.kyne.com.au/~mark/software/lua-cjson-manual.html).

In the Lua interpreter, I'm using an example from the cjson manual:

> local cjson = require "cjson"
> value = { true, { foo = "bar" } } 
> json_text = cjson.encode(value)
stdin:1: attempt to index a nil value (global 'cjson')
stack traceback:
    stdin:1: in main chunk
    [C]: in ?

I know that cjson is being found, because if I were to do ' require "foobar" ', Lua would error. It's just not able to use the module. Any help would be appreciated.

Cam Hashemi
  • 157
  • 1
  • 7

1 Answers1

2

Each line in an interactive session is a separate chunk. So, the local variable created in line 1 no longer exists in the next lines. Note how the error message mentions a global variable. Try removing local.

lhf
  • 70,581
  • 9
  • 108
  • 149
  • Thank you. Writing a Lua script with the above code worked, even with 'local' included. – Cam Hashemi Mar 30 '15 at 01:35
  • 2
    In a script, you are supposed to use `local` and avoid setting a global. I know it's confusing, but unfortunately due to this limitation of the interpreter, you are forced to use two different programming styles whether you're in the command line or a script. – Hisham H M Mar 30 '15 at 04:54