others-How to solve 'table expected,got userdata' error when trying to process a table in lua ?

1. Problem

Sometimes, when we try to process a table in lua, we got this error:

2022/04/27 19:51:32 [error] 4487#0: 
*2245086 [kong] init.lua:297 [basic-auth] /usr/local/share/lua/5.1/kong/plugins/common/utils.lua:72: 
bad argument #1 to 'next' (table expected, got userdata), 
client: 10.2.1.3, server: kong, 
request: "GET /test/hello/a HTTP/1.1", 
host: "10.2.2.4:8000"

Here is the code that cause the above error:


function isTableEmpty(t)
  return t==nil or (next(t)==nil)
end

local aValue = '{"a":123}'
isTableEmpty(aValue)



2. Solution

Here is the code that solves the error:

function isTableEmpty(t)
  return t==nil or (next(t)==nil)
end

local cjson = require 'cjson'
local aValue = '{"a":123}'
local theObject = cjson.decode(aValue)
isTableEmpty(theObject)

So the keypoint is to check if you have passed a non-table-object instead of a table to the function that needs a table.



3. Summary

In this post, I demonstrated how to solve ‘table expected,got userdata’ error when trying to process a table in lua. The keypoint is to check if you have passed a non-table-object instead of a table to the function that needs a table. That’s it, thanks for your reading.

-->