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

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.

share improve this question
 

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.

share improve this answer
 
 
Thank you. Writing a Lua script with the above code worked, even with 'local' included. –  Cam Hashemi Mar 30 '15 at 1: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 4:54
转自:https://stackoverflow.com/questions/29336895/lua-cjson-requirecjson-successful-then-errors-when-calling-cjson-encode


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值