# lua随机值



## 产生3以下的数字

```python
local count = 3
math.randomseed(os.time())
local index = math.random(count)
ngx.say(index);
```

## 产生 10\~13 的数字

```python
math.randomseed(os.time())
local index = math.random(10,13)
ngx.say(index);
```

```python
local res = ngx.location.capture_multi("http://baidu.com", {method = ngx.HTTP_GET,args = {a = 1, b = '2&'},body = 'c=3&d=4%26'})
ngx.say(res.body)
```

## 取出随机值

```python
function readRandomValueInTable(Table)
    math.randomseed(os.time())
    return Table[math.random(1,#Table)]
end

local tables = {'192.168.1.1','172.17.1.1','10.11.9.2'}
local postion = readRandomValueInTable(tables)
ngx.say(postion);
```

### 如果是哈希表要全部按key全部的话

```python
function readRandomValueInTable(Table)
    local tmpKeyT={}
    local n=1
    for k in pairs(Table) do
        tmpKeyT[n]=k
        n=n+1
    end
    math.randomseed(os.time())
    return Table[tmpKeyT[math.random(1,n-1)]]
end
```

```python
server
{
    listen 8080;
    lua_code_cache off;


    location /  {
      default_type 'text/plain';
      content_by_lua_file conf/lua/test.lua;
    }
}



# test.lua

local IPS = {'192.168.1.1','172.17.1.1','10.11.9.2'}


function readRandomValueInTable(Table)
    math.randomseed(os.time())
    return Table[math.random(1,#Table)]
end


function redictRewrite()
    math.randomseed(os.time())
    local _scheme = ngx.var.scheme
    local _redirect = readRandomValueInTable(IPS)
    local _port = math.random(1,1000)
    local _uri = ngx.var.request_uri
    return ngx.redirect(_scheme .. "://" .. _redirect .. ":" .. _port .. _uri)
    -- ngx.say(_scheme .. "://" .. _redirect .. ":" .. _port .. _uri);
end

redictRewrite()
```

```python
ngx.say(ngx.var['http_host'])       -- 输出变量 $http_host，请求头里的 
local args = nil

--- host = ngx.var.http_host
--- code = ngx.var.arg_code


if ngx.var.http_host = 'xxx.com' then
    ngx.redirect("https://baidu.com", 301)
end
```
