Skip to content

Commit

Permalink
improve: move try_read_attr function into table.lua (apache#2257)
Browse files Browse the repository at this point in the history
  • Loading branch information
starsz committed Oct 29, 2020
1 parent 960077f commit 9ebcfdf
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 14 deletions.
16 changes: 16 additions & 0 deletions apisix/core/table.lua
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,22 @@ function _M.set(tab, ...)
end


function _M.try_read_attr(tab, ...)
local count = select('#', ...)

for i = 1, count do
local attr = select(i, ...)
if type(tab) ~= "table" then
return nil
end

tab = tab[attr]
end

return tab
end


-- only work under lua51 or luajit
function _M.setmt__gc(t, mt)
local prox = newproxy(true)
Expand Down
15 changes: 1 addition & 14 deletions apisix/plugins/skywalking.lua
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ local math = math
local select = select
local type = type
local require = require
local try_read_attr = core.table.try_read_attr

local plugin_name = "skywalking"
local metadata_schema = {
Expand Down Expand Up @@ -103,20 +104,6 @@ function _M.log(conf, ctx)
end


local function try_read_attr(t, ...)
local count = select('#', ...)
for i = 1, count do
local attr = select(i, ...)
if type(t) ~= "table" then
return nil
end
t = t[attr]
end

return t
end


function _M.init()
if process.type() ~= "worker" and process.type() ~= "single" then
return
Expand Down
28 changes: 28 additions & 0 deletions t/core/table.t
Original file line number Diff line number Diff line change
Expand Up @@ -77,3 +77,31 @@ GET /t
ok
--- no_error_log
[error]



=== TEST 3: try_read_attr
--- config
location /t {
content_by_lua_block {
local core = require("apisix.core")
local try_read_attr = core.table.try_read_attr

local t = {level1 = {level2 = "value"}}

local v = try_read_attr(t, "level1", "level2")

ngx.say(v)

loval v2 = try_read_attr(t, "level1", "level3")

ngx.say(v2)
}
}
--- request
GET /t
--- response_body
"value"
""
--- no_error_log
[error]

0 comments on commit 9ebcfdf

Please sign in to comment.