Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua-cjson -> require("cjson") successful, then errors when calling cjson.encode

Tags:

json

lua

luarocks

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.

like image 538
Cam Hashemi Avatar asked Sep 10 '26 19:09

Cam Hashemi


1 Answers

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.

like image 178
lhf Avatar answered Sep 13 '26 22:09

lhf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!