How to get webp image EXIF metadata in lua? - lua

I can get this data with the following code. But it runs too slow:
local handle = io.popen("exiftool image.webp")
local result = handle:read("*a")
handle:close()
Is there a more elegant way to get the metadata?
UPD:
I use this software:
docker (20.10.7)
openresty/openresty:xenial (1.15.8.3)
luarocks (3.2.1)
LuaJIT (2.1.0-beta3)
Here is an example of a picture with a UserComment field: link
Exiftool sees this property:
$ exiftool -EXIF:UserComment Johnrogershousemay2020.webp
User Comment : {"foo":"bar"}

This method is less elegant, but it does not require to run external application :-)
function get_webp_user_comment(file_name)
local file = io.open(file_name, "rb")
local exif_offset, exif_found, is_big_endian, user_comment = 12
local function read_string(offset, size)
file:seek("set", offset)
return file:read(size)
end
local function read_uint(offset, size)
local n, s = 0, read_string(offset, size)
for j = 1, size do
n = n * 256 + s:byte(is_big_endian and j or size + 1 - j)
end
return n
end
local function read_uint32(disp)
return read_uint(exif_offset + disp, 4)
end
local function read_uint16(disp)
return read_uint(exif_offset + disp, 2)
end
local function search_for_tag(ifd_disp, tag)
if ifd_disp ~= 0 then
local entry_disp = ifd_disp + 2
for j = 1, read_uint16(ifd_disp) do
if read_uint16(entry_disp) == tag then
return read_uint32(entry_disp + 8), read_uint32(entry_disp + 4)
end
entry_disp = entry_disp + 12
end
return search_for_tag(read_uint32(entry_disp), tag)
end
end
if read_string(0, 4) == "RIFF" and read_string(8, 4) == "WEBP" then
local max_offset = read_uint32(-8)
while exif_offset < max_offset do
local section_name = read_string(exif_offset, 4)
exif_offset = exif_offset + 8
if section_name == "EXIF" then
local endianness = read_string(exif_offset, 2)
is_big_endian = endianness == "MM"
exif_found = is_big_endian or endianness == "II"
if exif_found then
break
end
end
exif_offset = exif_offset + read_uint32(-4)
exif_offset = exif_offset + exif_offset % 2
end
end
if exif_found then
local exif_ifd = search_for_tag(read_uint32(4), 0x8769)
if exif_ifd then
local disp, count = search_for_tag(exif_ifd, 0x9286)
user_comment = read_string(exif_offset + disp + 8, count - 8)
end
end
file:close()
return user_comment
end
Usage example:
local file_name = "path/to/Johnrogershousemay2020.webp"
print(get_webp_user_comment(file_name))

If all you need is 'UserComment', then pass that as a parameter during your popen call:
local handle = io.popen("exiftool -EXIF:UserComment image.webp")

Related

Lua Script problems on Super Nintendo emulation

I'm currently trying to run a lua script to find the future values of a static rng seed from "Fire Emblem - Seisen no Keifu" in the snes9x-1.52-rr-r185 emulator by reading the memory values.
Unfortunately I get the following message when i run the code: "rng.lua:26: attempt to call field 'text' (a nil value)"
The code is below:
emu = snes9x
function get_rng()
return {
step = memory.readbyte(0x7e04a2),
table = memory.readbyterange(0x7e046b,0x37)
}
end
function rand(rng)
rng.step = rng.step + 1
if rng.step >= 0x37 then
for i = 0, 0x36 do
local j if i < 0x18 then j = i+0x1f else j = i-0x18 end
rng.table[i+1] = rng.table[i+1] - rng.table[j+1]
if rng.table[i+1] < 0 then rng.table[i+1] = rng.table[i+1] + 100 end
end
rng.step = 0
end
local res = rng.table[rng.step+1]-1
if res < 0 then res = 99 end
return res
end
while true do
local rng = get_rng()
for i = 1, 0x10 do
gui.text(i*12, 0,string.format("%02x",rng.step))
gui.text(i*12,10,string.format("%2u",rand(rng)))
end
emu.frameadvance()
end
I expected the rng values to be shown on screen but got the aforementioned message.

Issue with a Lua Script

i really hope im right here, as on a discord server no one wants to help me for some reason.
We run a Project for a game called Garry's Mod and currently try to get a "Toxic Gas" Script Working.
But we face the following issue
[ERROR] gamemodes/zombierp/plugins/toxicgas/sh_plugin.lua:44: attempt to index local 'item' (a boolean value)
1. IsEquippingGasmask - gamemodes/zombierp/plugins/toxicgas/sh_plugin.lua:44
2. v - gamemodes/zombierp/plugins/toxicgas/sh_plugin.lua:121
3. unknown - gamemodes/helix/gamemode/core/libs/sh_plugin.lua:477
And me being fairly new to Lua, im just completly confused and dont know how to fix it.
Here is the Full Script
local config = {
smokeColor = Color(63, 127, 0),
smokeAlpha = 110,
maskItem = "gasmask",
smokeSpawnerDistance = 100 -- distance between the smoke emitters on the box line
}
local PLUGIN = PLUGIN
PLUGIN.name = "Toxic Gas"
PLUGIN.author = ""
PLUGIN.description = ""
PLUGIN.positions = PLUGIN.positions or {}
PLUGIN.smokeStacks = PLUGIN.smokeStacks or {}
function PLUGIN:LoadData()
PLUGIN.positions = self:GetData()
self:UpdateWorldData()
end
function PLUGIN:SaveData()
self:SetData(PLUGIN.positions)
self:UpdateWorldData()
end
function PLUGIN:UpdateWorldData()
SetNetVar("toxicGasPositions", PLUGIN.positions)
-- global netvar doesn't seem to sync without this
for _, ply in pairs(player.GetAll()) do
ply:SyncVars()
end
end
function PLUGIN:IsEquippingGasmask(ply)
local character = ply:GetCharacter()
if not character then return false end
local inventoryID = character:GetInventory():GetID()
local inventory = ix.item.inventories[inventoryID]
for x, items in pairs(inventory.slots) do
for y, item in pairs(items) do
if item.uniqueID == config.maskItem
and item:GetData("equip") == true then
return true
end
end
end
return false
end
local function GetBoxLine(min, max)
local deltaX = math.abs(min.x - max.x)
local deltaY = math.abs(min.y - max.y)
local lineStart, lineEnd
if deltaX < deltaY then
lineStart = Vector(min.x + (max.x - min.x) / 2, min.y, min.z)
lineEnd = Vector(min.x + (max.x - min.x) / 2, min.y + (max.y - min.y), min.z)
else
lineStart = Vector(min.x, min.y + (max.y - min.y) / 2, min.z)
lineEnd = Vector(min.x + (max.x - min.x), min.y + (max.y - min.y) / 2, min.z)
end
return lineStart, lineEnd
end
if SERVER then
function PLUGIN:Think()
for idx, gasBox in pairs(PLUGIN.positions) do
if PLUGIN.smokeStacks[idx] == nil then
local min, max = gasBox.min, gasBox.max
local startSmoke, endSmoke = GetBoxLine(min, max)
PLUGIN.smokeStacks[idx] = {
count = math.floor(startSmoke:Distance(endSmoke) / config.smokeSpawnerDistance),
stacks = {}
}
for i = 1, PLUGIN.smokeStacks[idx].count do
local smoke = ents.Create("env_smokestack")
smoke:SetPos(startSmoke + (endSmoke - startSmoke):GetNormalized() * (i) * config.smokeSpawnerDistance)
smoke:SetKeyValue("InitialState", "1")
smoke:SetKeyValue("WindAngle", "0 0 0")
smoke:SetKeyValue("WindSpeed", "0")
smoke:SetKeyValue("rendercolor", tostring(config.smokeColor))
smoke:SetKeyValue("renderamt", tostring(config.smokeAlpha))
smoke:SetKeyValue("SmokeMaterial", "particle/particle_smokegrenade.vmt")
smoke:SetKeyValue("BaseSpread", tostring(config.smokeSpawnerDistance))
smoke:SetKeyValue("SpreadSpeed", "10")
smoke:SetKeyValue("Speed", "32")
smoke:SetKeyValue("StartSize", "32")
smoke:SetKeyValue("EndSize", "32")
smoke:SetKeyValue("roll", "8")
smoke:SetKeyValue("Rate", "64")
smoke:SetKeyValue("JetLength", tostring(max.z - min.z))
smoke:SetKeyValue("twist", "6")
smoke:Spawn()
smoke:Activate()
smoke.Think = function()
if PLUGIN.positions[idx] == nil then
smoke:Remove()
end
end
PLUGIN.smokeStacks[idx].stacks[i] = smoke
end
end
end
for _, ply in pairs(player.GetAll()) do
local pos = ply:EyePos()
if not ply:Alive() then continue end
local canBreathe = false
if not canBreathe then
canBreathe = self:IsEquippingGasmask(ply)
end
if not canBreathe then
for _, gasBox in pairs(PLUGIN.positions) do
if pos:WithinAABox(gasBox.min, gasBox.max) then
ply.nextGasDamage = ply.nextGasDamage or CurTime()
if CurTime() >= ply.nextGasDamage then
ply.nextGasDamage = CurTime() + .75
ply:TakeDamage(6)
ix.util.Notify("You are choking. You need a gas mask.", ply)
end
break
end
end
end
end
end
end
if CLIENT then
-- toggles showing toxic gas boxes when in noclip/observer
CreateConVar("ix_toxicgas_observer", "0", FCVAR_ARCHIVE)
local function IsInRange(min, max, scale)
local localPos = LocalPlayer():GetPos()
local distance = min:Distance(max)
if localPos:Distance(min + ((max - min) / 2)) <= distance * scale then
return true
end
return false
end
function PLUGIN:PostDrawTranslucentRenderables()
local toxicGasPositions = GetNetVar("toxicGasPositions")
if toxicGasPositions == nil then return end
for _, gasBox in pairs(toxicGasPositions) do
local min, max = gasBox.min, gasBox.max
if not IsInRange(min, max, 3) then continue end
local observerCvar = GetConVar("ix_toxicgas_observer")
if LocalPlayer():IsAdmin()
and LocalPlayer():GetMoveType() == MOVETYPE_NOCLIP
and observerCvar and observerCvar:GetBool() then
render.DrawWireframeBox(min, Angle(), Vector(0, 0, 0), max - min, Color(142, 222, 131, 255), false)
local startSmoke, endSmoke = GetBoxLine(min, max)
render.DrawLine(startSmoke, endSmoke, Color(0, 255, 0), false)
end
end
end
function PLUGIN:HUDPaint()
-- this is an FPS killer tbh
--[[
local toxicGasPositions = game.GetWorld():GetNetVar("toxicGasPositions")
if toxicGasPositions == nil then return end
local inToxicGas = false
local center
local cornerDist
for _, gasBox in pairs(toxicGasPositions) do
local min, max = gasBox.min, gasBox.max
center = min + ((max - min) / 2)
cornerDist = min:Distance(max)
if LocalPlayer():EyePos():WithinAABox(min, max) then
inToxicGas = true
continue
end
end
if inToxicGas then
local isEquippingGasmask = self:IsEquippingGasmask(LocalPlayer())
local distance = LocalPlayer():EyePos():Distance(center)
ix.util.DrawBlurAt(0, 0, ScrW(), ScrH(), 1, 0.2, isEquippingGasmask and 50 or 255)
end
]]
end
end
ix.command.Add("AddToxicGas", {
description = "Adds a toxic gas box from where you're standing and where you're looking at.",
adminOnly = true,
OnRun = function(self, client)
local pos = client:GetPos()
local tr = client:GetEyeTrace()
if not tr then return end
local hitPos = tr.HitPos
table.insert(PLUGIN.positions, {
min = pos, max = hitPos
})
PLUGIN:SaveData()
return "Added toxic gas."
end
})
ix.command.Add("RemoveToxicGas", {
description = "Removes the closest toxic gas point relative to you.",
adminOnly = true,
OnRun = function(self, client)
local closestDistance = -1
local closestIndex = -1
for idx, gasBox in pairs(PLUGIN.positions) do
local min, max = gasBox.min, gasBox.max
local center = min + ((max - min) / 2)
local distance = client:GetPos():Distance(center)
if closestDistance == -1 or distance < closestDistance then
closestDistance = distance
closestIndex = idx
end
end
if closestIndex ~= -1 then
table.remove(PLUGIN.positions, closestIndex)
if PLUGIN.smokeStacks[closestIndex] then
for k, v in pairs(PLUGIN.smokeStacks[closestIndex].stacks) do
v:Remove()
end
table.remove(PLUGIN.smokeStacks, closestIndex)
end
PLUGIN:SaveData()
return "Removed 1 toxic gas box."
else
return "Could not find any toxic gas to remove!"
end
end
})
I Really hope someone can help me with that as im trying since 2 days now
Try replacing for y, item in pairs(items) do with for item, _ in pairs(items) do.
Reason: there is a chance that items is a set, i.e., a Lua table, in which keys are set members and values are true.
change line 44
if item.uniqueID == config.maskItem
either by refusing boolean values
if type(item) ~= 'boolean' and item.uniqueID == config.maskItem
or only allowing tables, because they could possibly contain .uniqueID
if type(item) == 'table' and item.uniqueID == config.maskItem

How to get over the 32 bits for storing numbers like - 2,147,483,647 to 2,147,483,647

I try to fix some old Basewars script for Gmod amd there is something i tried to fix but i dont know what i am missing there. Basicly its about a Bank script. This Bank could original store a amount of 2 Billion $. I would like to expand that storage amount to 1 Quadtrillion.
So Basicly the Basewars Gamemode allows players to have an high amount of money up to 10^18 $
= 1 Quintillion. I looked up into https://wiki.garrysmod.com/page/Category:number
so basicly lua uses double-precision floating-point format. So lua uses 32 bits for storing numbers and that means the number can be from a range of
-2,147,483,647 to 2,147,483,647.
The Basewars Gamemode uses a Function to make out of 10^18
= 1 Quintillion
function BaseWars.NumberFormat(num)
local t = BaseWars.LANG.Numbers
for i = 1, #t do
local Div = t[i][1]
local Str = t[i][2]
if num >= Div or num <= -Div then
return string.Comma(math.Round(num / Div, 1)) .. " " .. Str
end
end
return string.Comma(math.Round(num, 1))
end
The Gamemode is using that faction to convert the amount of money.
and here is the BaseWars.LANG.Numbers:
BaseWars.LANG = {}
BaseWars.LANG.__LANGUAGELOOK = {}
BaseWars.LANG.__LANGUAGELOOK.ENGLISH = {
Numbers = {
[5] = {10^6, "Million"},
[4] = {10^9, "Billion"},
[3] = {10^12, "Trillion"},
[2] = {10^15, "Quadtillion"},
[1] = {10^18, "Quintillion"},
},
CURFORMER = CURRENCY .. "%s",
CURRENCY = CURRENCY,
}
So i know that this function does work but i dont get it, how the variable num can be that high!
Why do i know what it does work ?
Here is what i tried and it manipulated the Capacity up to 1 Quadtrillion but at the point i manipluated a other Problem came up and i do not know what i do wrong!
Here how it was Original:
ENT.Capacity = 2000000000 --Max money in the bank. Can be bugs if it is more than 2000000000 (2 bil)
ENT.Money = 0
ENT.MaxPaper = 0
local Clamp = math.Clamp
function ENT:GSAT(slot, name, min, max)
self:NetworkVar("Int", slot, name)
local getVar = function(minMax)
if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end
if self[minMax] and isnumber(self[minMax]) then return self[minMax] end
return minMax or 0
end
self["Add" .. name] = function(_, var)
local Val = self["Get" .. name](self) + var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
self["Take" .. name] = function(_, var)
local Val = self["Get" .. name](self) - var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
end
function ENT:StableNetwork()
self:GSAT(2, "Capacity")
self:GSAT(3, "Money", 0, "GetCapacity")
self:GSAT(4, "Paper", 0, "MaxPaper")
self:GSAT(5, "Level", 0, "MaxLevel")
end
function ENT:ThinkFunc() --This Funtion is to auto collect all the Money of Printers
for k, v in pairs( ents.FindByClass( "bw_printer_*" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < self.Capacity then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
for k, v in pairs( ents.FindByClass( "bw_base_moneyprinter" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < self.Capacity then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
end
if CLIENT then
local Cp = self:GetCapacity()
local money = tonumber(self:GetMoney()) or 0
local cap = tonumber(Cp) or 0
local moneyPercentage = math.Round( money / cap * 100 ,1)
draw.DrawText( moneyPercentage .."%" , fontName .. ".Huge", w - 4-430, 71+610, self.FontColor, TEXT_ALIGN_CENTER)
local currentMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(money)
local maxMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap)
local font = fontName .. ".Big"
if #currentMoney > 16 then
font = fontName .. ".MedBig"
end
if #currentMoney > 20 then
font = fontName .. ".Med"
end
local fh = draw.GetFontHeight(font)
local StrW,StrH = surface.GetTextSize("")
local moneyW,moneyH = surface.GetTextSize(currentMoney)
draw.DrawText(currentMoney.. " / " .. BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap) , font,
w/2 - StrW/2-225 , (font == fontName .. ".Big" and 106 or 105 + fh / 4)+675, self.FontColor, TEXT_ALIGN_CENTER)
end
Here the changes i did:
removed line:
local cap = tonumber(Cp) or 0
added
local cap = 10^15
if self:GetMoney() < cap then
ENT.Capacity = 2000000000 --Max money in the bank. Can be bugs if it is more than 2000000000 (2 bil)
local cap = 10^15
ENT.Money = 0
ENT.MaxPaper = 0
local Clamp = math.Clamp
function ENT:GSAT(slot, name, min, max)
self:NetworkVar("Int", slot, name)
local getVar = function(minMax)
if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end
if self[minMax] and isnumber(self[minMax]) then return self[minMax] end
return minMax or 0
end
self["Add" .. name] = function(_, var)
local Val = self["Get" .. name](self) + var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
self["Take" .. name] = function(_, var)
local Val = self["Get" .. name](self) - var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), getVar(max))
end
self["Set" .. name](self, Val)
end
end
function ENT:StableNetwork()
self:GSAT(2, "Capacity")
self:GSAT(3, "Money", 0, "GetCapacity")
self:GSAT(4, "Paper", 0, "MaxPaper")
self:GSAT(5, "Level", 0, "MaxLevel")
end
function ENT:ThinkFunc() --This Funtion is to auto collect all the Money of Printers
for k, v in pairs( ents.FindByClass( "bw_printer_*" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < cap then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
for k, v in pairs( ents.FindByClass( "bw_base_moneyprinter" ) ) do
if v:CPPIGetOwner() == self:CPPIGetOwner() then
if self:GetMoney() < cap then
local allmoney = v:GetMoney()
v:TakeMoney(allmoney)
self:AddMoney(allmoney)
end
end
end
end
if CLIENT then
local Cp = self:GetCapacity()
local money = tonumber(self:GetMoney()) or 0
local moneyPercentage = math.Round( money / cap * 100 ,1)
draw.DrawText( moneyPercentage .."%" , fontName .. ".Huge", w - 4-430, 71+610, self.FontColor, TEXT_ALIGN_CENTER)
local currentMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(money)
local maxMoney = BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap)
local font = fontName .. ".Big"
if #currentMoney > 16 then
font = fontName .. ".MedBig"
end
if #currentMoney > 20 then
font = fontName .. ".Med"
end
local fh = draw.GetFontHeight(font)
local StrW,StrH = surface.GetTextSize("")
local moneyW,moneyH = surface.GetTextSize(currentMoney)
draw.DrawText(currentMoney.. " / " .. BaseWars.LANG.CURRENCY .. BaseWars.NumberFormat(cap) , font,
w/2 - StrW/2-225 , (font == fontName .. ".Big" and 106 or 105 + fh / 4)+675, self.FontColor, TEXT_ALIGN_CENTER)
end
So now if you i look into the game it looks like this:
and now i have the problem that when it collects money it does it up to 2 billion and if i try to change
local money = tonumber(self:GetMoney()) or 0
to
local money =self:GetMoney()
i get straight -2.1 Bil
or i tried to change the min max values:
function ENT:GSAT(slot, name, min, max)
self:NetworkVar("Int", slot, name)
local getVar = function(minMax)
if self[minMax] and isfunction(self[minMax]) then return self[minMax](self) end
if self[minMax] and isnumber(self[minMax]) then return self[minMax] end
return minMax or 0
end
self["Add" .. name] = function(_, var)
local Val = self["Get" .. name](self) + var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), 10^15)
end
self["Set" .. name](self, Val)
end
self["Take" .. name] = function(_, var)
local Val = self["Get" .. name](self) - var
if min and max then
Val = Clamp(tonumber(Val) or 0, getVar(min), 10^15)
end
self["Set" .. name](self, Val)
end
end
Basicly these lines:
Val = Clamp(tonumber(Val) or 0, getVar(min), 10^15)
if i run the game the Bank will just collect the money up to 2 Bill and then it goes to -2.1Bil. And at that point i dont know why and when a value does go buggy like it self sets to -2.1 Bil. does math.Round create this bug or do funktion return only return full integer ?
thx for any help
Because the network variable that the bank uses is an integer, it will only be able to store $(2^31-1) through $-(2^31-1). Try changing it to a networked float:
-- ...
function ENT:GSAT(slot, name, min, max)
-- self:NetworkVar("Int", slot, name), changes into:
self:NetworkVar("Float", slot, name)
-- ...
But, beware as the more money players accumulate the less precision will be put into those numbers.

Is there a way for numbers to exceed the integer max in lua using string values?

I'm talking about rbx.Lua so if you don't know it well, don't try to answer this
function ConvertShort(num, cool)
local x = tostring(num)
if #x >= 16 then
local important = (#x - 15)
cool.Value = x:sub(0,(important)).."."..(x:sub(#x-13,(#x-13))).."qd"
elseif #x >= 13 then
local important = (#x-12)
cool.Value = x:sub(0,(important)).."."..(x:sub(#x-10,(#x-10))).."T"
elseif #x>= 10 then
local important = (#x - 9)
cool.Value = x:sub(0,(important)).."."..(x:sub(#x-7,(#x-7))).."B"
elseif #x >= 7 then
local important = (#x-6)
cool.Value = x:sub(0,(important)).."."..(x:sub(#x-5,(#x-5))).."M"
elseif #x >= 4 then
cool.Value = x:sub(0,(#x-3)).."."..(x:sub(#x-2,(#x-2))).."k"
end
end
game.Players.PlayerAdded:connect(function(plr)
local cash = Instance.new("StringValue", plr)
cash.Name = "cash"
cash.Value = "0"
cash.Changed:connect(function()
ConvertShort(tonumber(cash.Value), cash)
end)
end)
So, when it gets to quadrillions it shows a nubmer like 1e+1.1k, which is not what I'm needing it to be like, I need it to be more like "1qd", and I have no idea how to fix this or if there even is a way.
Replace
local x = tostring(num)
with this code:
local x = ""
while num >= 1000000 do
x, num = x.."0", math.floor(num / 10)
end
x = tostring(num)..x
Replace
local x = tostring(num)
with
local x = string.format("%.0f", num)

Lua (Lapis) random values returns the same result even using randomseed

At first, I use this:
math.randomseed(os.time())
This function to check:
function makeString(l)
if l < 1 then return nil end
local s = ""
for i = 0, l do
n = math.random(0, 61)--61
n0 = 0
if n < 10 then n0 = n + 48
elseif n < 36 then n0 = n - 10 + 65
else n0 = n - 36 + 97 end
s = s .. string.char(n0)
end
return s
end
If I use this function:
app:match("/tttt", function()
local ss = ""
for i=1,10 do ss = ss .. makeString(30) .. "\n" end
return ss
end)
I receive good different values.
If I use this:
app:match("/ttt", function()
return makeString(30)
end)
and JavaScript jQuery,
:
$("#button5").click(function(){
var ss = ""
for(var i = 0; i < 10; i++)
{
$("#div1").load("/ttt", function() {
ss = ss + $(this).text()
alert(ss);
});
}
$("#div1").text(ss);
});
I recieve the same random strings every one second.
How to fix it? I tried to create database with different random data but I recieve the same strings!!! This is just example I wrote but filling the database gives the same result!##%%
Any ideas to fix it?
I found that this is "feature" of lua to generate random using seconds. Use this link to read more: http://lua-users.org/wiki/MathLibraryTutorial
But the solution which can help is to user /dev/urandom
The link to describe:
http://lua-users.org/lists/lua-l/2008-05/msg00498.html
In my case example:
local frandom = io.open("/dev/urandom", "rb")
local makeString
makeString = function(l)
local d = frandom:read(4)
math.randomseed(d:byte(1) + (d:byte(2) * 256) + (d:byte(3) * 65536) + (d:byte(4) * 4294967296))
if l < 1 then return nil end
local s = ""
for i = 0, l do
local n = math.random(0, 61)
n0 = 0
if n < 10 then n0 = n + 48
elseif n < 36 then n0 = n - 10 + 65
else n0 = n - 36 + 97 end
s = s .. string.char(n0)
end
return s
end

Resources