Sankalp
Sankalp

Reputation: 1288

Return a boolean from lua nginx module's set_by_lua_block method

I'm using lua nginx module in my nginx conf file. I'm trying to set a value variable during runtime depending on some injected parameters. However, I can not return a boolean from the block without converting it into a string. I'm trying to optimize this part by trying to remove this redundant string conversion.

This one works

location /set_by_lua_block_example {
             set_by_lua_block $value {
                return tostring(false)
             }
             
             add_header X-value "$value";

             content_by_lua_block {
                 ngx.say('Printing from set_by_lua_block_example!')
             }
        }

But this one doesn't.

location /set_by_lua_block_example {
             set_by_lua_block $value {
                return false
             }
             
             add_header X-value "$value";

             content_by_lua_block {
                 ngx.say('Printing from set_by_lua_block_example!')
             }
        }

Upvotes: 0

Views: 1106

Answers (1)

Aki
Aki

Reputation: 2938

The set_by_lua family of functions expect string output as per:

syntax: set_by_lua $res [$arg1 $arg2 ...]

Executes code specified in <lua-script-str> (...) and returns string output to $res.

This applies to set_by_lua_block, too.

Moreover, note that the conversion is not redundant in your case. You use that value later in a HTTP header which is text.

Now, why explicit tostring(boolean) is needed? That's because lua_tolstring is used to retrieve returned value. This function (and tostring variant) accepts only strings and numbers.

If you want to store values for use in another Lua block consider using ngx.ctx.

Upvotes: 0

Related Questions