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

来源:互联网 发布:软件项目管理课程设计 编辑:程序博客网 时间:2024/04/30 12:42

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.

shareimprove this question
 

1 Answer

activeoldest votes
up vote1 down vote

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 aglobal variable. Try removing local.

shareimprove 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 uselocal 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


原创粉丝点击