Nginx (openresty) generating random numbers

Mediocre Gopher asked:

I have openresty set up on a server (nginx bundle which includes the lua module) and I’m trying to create a script which has specific odds of setting a cookie on a user’s browser. My code looks like this:

    location =/index.php {
        set $random_num 0;

        rewrite_by_lua '

                marth.randomseed(1);
                nvx.var.random_num = math.random(0,3);

        ';

        add_header Set-Cookie "random_num=$random_num; path=/; domain=...com;";
    }

I know my random seed function isn’t actually very random, but I figured I’d deal with that later. At the moment I’m just trying to get nginx to set a random number, but doing so yields this error:

2012/07/11 11:27:20 [error] 5492#0: *44 lua handler aborted: runtime error: [string "rewrite_by_lua"]:3: attempt to ind
ex global 'marth' (a nil value)
stack traceback:

Can anyone tell me what I’m doing wrong, and if there’s any other way to get a random number in nginx?

My answer:


Based on your error log entry, it appears you have a simple typo.

            marth.randomseed(1);

This should read:

            math.randomseed(1);

View the full question and answer on Server Fault.

Creative Commons License
This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.