How to print the result of calculation lua - lua

Local cl = rendom - or +
Local a = rendom number
Local x = rendom number
Locol re = a..cl..x
Print (re) --output 5+8
I need to get the result 13
How to do that?

If you want the number 13 you can try:
Local cl = rendom "m" or "p" -- m for -, p for +
Local a = rendom number
Local x = rendom number
Local re = 0
if cl == "m" then re = a-x end
if cl == "p" then re = a+x end
Print (re) --output 13
or
Local cl = rendom "m" or "p" -- m for -, p for +
Local a = rendom number
Local x = rendom number
Local re = 0
if cl == "m" then re = a-x Print(a.."-"..x, re) end
if cl == "p" then re = a+x Print(a.."+"..x, re) end
Hope this helps!

Related

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.

Parsing Lua strings, more specifically newlines

I'm trying to parse Lua 5.3 strings. However, I encountered an issue. For example,
$ lua
Lua 5.3.4 Copyright (C) 1994-2017 Lua.org, PUC-Rio
> print(load('return "\\z \n\r \n\r \r\n \n \n \\x"', "#test"))
nil test:6: hexadecimal digit expected near '"\x"'
>
> print(load('return "\\z\n\r\n\r\r\n\n\n\\x"', "#test"))
nil test:6: hexadecimal digit expected near '"\x"'
Both of these error on line 6, and the logic behind that is pretty simple: eat newline characters (\r or \n) if they're different from the current one (I believe this to be an accurate description of how the lua lexer works, but I may be wrong).
I have this code, which should do it:
local ln = 1
local skip = false
local mode = 0
local prev
for at, crlf in eaten:gmatch('()[\r\n]') do
local last = eaten:sub(at-1, at-1)
if skip and prev == last and last ~= crlf then
skip = false
else
skip = true
ln = ln + 1
end
prev = crlf
end
It decides whether to eat newlines based on the previous char. Now, from what I can tell, this should work, but no matter what I do it doesn't seem to work. Other attempts have made it report 5 lines, while this one makes it report 9(!). What am I missing here? I'm running this on Lua 5.2.4.
This is part of a routine for parsing \z:
local function parse52(s)
local startChar = string.sub(s,1,1)
if startChar~="'" and startChar~='"' then
error("not a string", 0)
end
local c = 0
local ln = 1
local t = {}
local nj = 1
local eos = #s
local pat = "^(.-)([\\" .. startChar .. "\r\n])"
local mkerr = function(emsg, ...)
error(string.format('[%s]:%d: ' .. emsg, s, ln, ...), 0)
end
local lnj
repeat
lnj = nj
local i, j, part, k = string.find(s, pat, nj + 1, false)
if i then
c = c + 1
t[c] = part
if simpleEscapes[v] then
--[[ some code, some elseifs, some more code ]]
elseif v == "z" then
local eaten, np = s:match("^([\t\n\v\f\r ]*)%f[^\t\n\v\f\r ]()", nj+1)
local p=np
nj = p-1
--[[ the newline counting routine above ]]
--[[ some other elseifs ]]
end
else
nj = nil
end
until not nj
if s:sub(-1, -1) ~= startChar then
mkerr("unfinished string near <eof>")
end
return table.concat(t)
end
Compact code for iterating lines of Lua script:
local text = "First\n\r\n\r\r\n\n\nSixth"
local ln = 1
for line, newline in text:gmatch"([^\r\n]*)([\r\n]*)" do
print(ln, line)
ln = ln + #newline:gsub("\n+", "\0%0\0"):gsub(".%z.", "."):gsub("%z", "")
end
Efficient code for iterating lines of Lua script:
local text = "First\n\r\n\r\r\n\n\nSixth"
local sub = string.sub
local ln = 1
for line, newline in text:gmatch'([^\r\n]*)([\r\n]*)' do
print(ln, line)
local pos, max_pos = 1, #newline
while pos <= max_pos do
local crlf = sub(newline, pos, pos + 1)
if crlf == "\r\n" or crlf == "\n\r" then
pos = pos + 2
else
pos = pos + 1
end
ln = ln + 1
end
end

Convert Table string to the actual table

local t = "{{2173,1},{2160,5}}"
print(#t) -- 19?? wrong
How to convert to appear in numbers?
local t = {{2173,1},{2160,5}}
print(#t) -- 2 correct
You can run the string through load or loadstring (depending on your Lua version), which will return the table you are looking for:
local t = "{{2173,1},{2160,5}}"
t = (loadstring or load)("return "..t)()
print(#t) -- 2
Here is an ad hoc solution for the input you gave:
local s = "{{2173,1},{2160,5}}"
local t = {}
local n = 0
for a,b in s:gmatch("(%d+),(%d+)") do
n = n + 1
t[n] = {a,b}
end
for k,v in ipairs(t) do print(k,v[1],v[2]) end

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)

Get a certain value from a concatenated table

Trying to allow a concatenated table to be referenced as such:
local group = table.concat(arguments, ",", 1)
where arguments = {"1,1,1"}
Currently, doing group[2] gives me the comma. How do I avoid that while still allowing for two-digit numbers?
(snippet of what I'm trying to use it for)
for i = 1, #group do
target:SetGroup(i, tonumber(group[i]))
end
Maybe you want something like
local i = 1
for v in string.gmatch(s, "(%w+),*") do
group[i] = v
i = i + 1
end
Revised version in response to comment, avoiding the table altogether:
local i = 1
for v in string.gmatch(s, "(%w+),*") do
target:SetGroup(i, tonumber(v))
i = i + 1
end
split function (you have to add it to code)
split = function(str, delim)
if not delim then
delim = " "
end
-- Eliminate bad cases...
if string.find(str, delim) == nil then
return { str }
end
local result = {}
local pat = "(.-)" .. delim .. "()"
local nb = 0
local lastPos
for part, pos in string.gfind(str, pat) do
nb = nb + 1
result[nb] = part
lastPos = pos
end
-- Handle the last field
result[nb + 1] = string.sub(str, lastPos)
return result
end
so
local arguments = {"1,1,1"};
local group = split(arguments[1], ",");
for i = 1, #group do
target:SetGroup(i, tonumber(group[i]))
end
also note that
local arguments = {"1,1,1"};
local group = split(arguments[1], ",");
local group_count = #group;
for i = 1, group_count do
target:SetGroup(i, tonumber(group[i]))
end
is faster code ;)

Resources