Find the string length of a Lua number? - lua

Easy question here, probably, but searching did not find a similar question.
The # operator finds the length of a string, among other things, great. But with Lua being dynamically typed, thus no conversion operators, how does one type a number as a string in order to determine its length?
For example suppose I want to print the factorials from 1 to 9 in a formatted table.
i,F = 1,1
while i<10 do
print(i.."! == "..string.rep("0",10-#F)..F)
i=i+1
F=F*i
end
error: attempt to get length of global 'F' (a number value)

why not use tostring(F) to convert F to a string?

Alternatively,
length = math.floor(math.log10(number)+1)
Careful though, this will only work where n > 0!

There are probably a dozen ways to do this. The easy way is to use tostring as Dan mentions. You could also concatenate an empty string, e.g. F_str=""..F to get F_str as a string representation. But since you are trying to output a formatted string, use the string.format method to do all the hard work for you:
i,F = 1,1
while i<10 do
print(string.format("%01d! == %010d", i, F))
i=i+1
F=F*i
end

Isn't while tostring(F).len < 10 do useful?

Related

Finding the number of digits in a number restricted number of tools since I am a Python beginner

def digits(n):
total=0
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))=>1:
total+=i
else:
total+=0
return total
I want to find the number of digits in 13 so I do the below
print digits(13)
it gives me $\0$ for every number I input into the function.
there's nothing wrong with what I've written as far as I can see:
if a number has say 4 digits say 1234 then dividing by 10^4 will make it less than 1: 0.1234 and dividing by 10^3 will make it 1.234
and by 10^3 will make it 1.234>1. when i satisfies BOTH conditions you know you have the correct number of digits.
what's failing here? Please can you advise me on the specific method I've tried
and not a different one?
Remember for every n there can only be one i which satisfies that condition.
so when you add i to the total there will only be i added so total returning total will give you i
your loop makes no sense at all. It goes from 0 to exact number - not what you want.
It looks like python, so grab a solution that uses string:
def digits(n):
return len(str(int(n))) # make sure that it's integer, than conver to string and return number of characters == number of digits
EDIT:
If you REALLY want to use a loop to count number of digits, you can do this this way:
def digits(n):
i = 0
while (n > 1):
n = n / 10
++i
return i
EDIT2:
since you really want to make your solution work, here is your problem. Provided, that you call your function like digits(5), 5 is of type integer, so your division is integer-based. That means, that 6/100 = 0, not 0.06.
def digits(n):
for i in range(0,n):
if n/float(10**(i))<1 and n/float(10**(i-1))=>1:
return i # we don't need to check anything else, this is the solution
return null # we don't the answer. This should not happen, but still, nice to put it here. Throwing an exception would be even better
I fixed it. Thanks for your input though :)
def digits(n):
for i in range(0,n):
if n/(10**(i))<1 and n/(10**(i-1))>=1:
return i

Convert Table Elements to Integers

I'm trying to create a list of integers, similar to python where one would say
x = input("Enter String").split() # 1 2 3 5
x = list(map(int,x)) # Converts x = "1","2",3","5" to x = 1,2,3,5
Here's my code asking for the input, then splitting the input into a table, i need help converting the contents of the table to integers as they're being referenced later in a function, and i'm getting a string vs integer comparison error. I've tried changing the split for-loop to take a number but that doesn't work, I'm familiar with a python conversion but not with Lua so I'm looking for some guidance in converting my table or handling this better.
function main()
print("Hello Welcome the to Change Maker - LUA Edition")
print("Enter a series of change denominations, separated by spaces")
input = io.read()
deno = {}
for word in input:gmatch("%w+") do table.insert(deno,word) end
end
--Would This Work?:
--for num in input:gmatch("%d+") do table.insert(deno,num) end
Just convert your number-strings to numbers using tonumber
local number = tonumber("1")
So
for num in input:gmatch("%d+") do table.insert(deno,tonumber(num)) end
Should do the trick

Find all upper/lower/mixed combinations of a string

I need this for a game server using Lua..
I would like to be able to save all combinations of a name
into a string that can then be used with:
if exists (string)
example:
ABC_-123
aBC_-123
AbC_-123
ABc_-123
abC_-123
etc
in the game only numbers, letters and _ - . can be used as names.
(A_B-C, A-B.C, AB_8 ... etc)
I understand the logic I just don't know how to code it:D
0-Lower
1-Upper
then
000
001
etc
You can use recursive generator. The first parameter contains left part of the string generated so far, and the second parameter is the remaining right part of the original string.
function combinations(s1, s2)
if s2:len() > 0 then
local c = s2:sub(1, 1)
local l = c:lower()
local u = c:upper()
if l == u then
combinations(s1 .. c, s2:sub(2))
else
combinations(s1 .. l, s2:sub(2))
combinations(s1 .. u, s2:sub(2))
end
else
print(s1)
end
end
So the function is called in this way.
combinations("", "ABC_-123")
You only have to store intermediate results instead of printing them.
If you are interested only in the exists function then you don't need all combinations.
local stored_string = "ABC_-123"
function exists(tested_string)
return stored_string:lower() == tested_string:lower()
end
You simply compare the stored string and the tested string in case-insensitive way.
It can be easily tested:
assert(exists("abC_-123"))
assert(not exists("abd_-123"))
How to do this?
There's native function in Lua to generate all permutations of a string, but here are a few things that may prove useful.
Substrings
Probably the simplest solution, but also the least flexible. Rather than combinations, you can check if a substring exists within a given string.
if str:find(substr) then
--code
end
If this solves your problem, I highly reccomend it.
Get all permutations
A more expensive, but still a working solution. This accomplishes nearly exactly what you asked.
function GetScrambles(str, tab2)
local tab = {}
for i = 1,#str do
table.insert(tab, str:sub(i, i))
end
local tab2 = tab2 or {}
local scrambles = {}
for i = 0, Count(tab)-1 do
local permutation = ""
local a = Count(tab)
for j = 1, #tab do
tab2[j] = tab[j]
end
for j = #tab, 1, -1 do
a = a / j
b = math.floor((i/a)%j) + 1
permutation = permutation .. tab2[b]
tab2[b] = tab2[j]
end
table.insert(scrambles, permutation)
end
return scrambles
end
What you asked
Basically this would be exactly what you originally asked for. It's the same as the above code, except with every substring of the string.
function GetAllSubstrings(str)
local substrings = {}
for i = 1,#str do
for ii = i,#str do
substrings[#substrings+1]=str:sub(ii)
end
end
return substrings
end
Capitals
You'd basically have to, with every permutation, make every possible combination of capitals with it.
This shouldn't be too difficult, I'm sure you can code it :)
Are you joking?
After this you should probably be wondering. Is all of this really necessary? It seems like a bit much!
The answer to this lies in what you are doing. Do you really need all the combinations of the given characters? I don't think so. You say you need it for case insensitivity in the comments... But did you know you could simply convert it into lower/upper case? It's very simple
local str = "hELlO"
print(str:lower())
print(str:upper())
This is HOW you should store names, otherwise you should leave it case sensitive.
You decide
Now YOU pick what you're going to do. Whichever direction you pick, I wish you the best of luck!

lua - table.concat with string keys

I'm having a problem with lua's table.concat, and suspect it is just my ignorance, but cannot find a verbose answer to why I'm getting this behavior.
> t1 = {"foo", "bar", "nod"}
> t2 = {["foo"]="one", ["bar"]="two", ["nod"]="yes"}
> table.concat(t1)
foobarnod
> table.concat(t2)
The table.concat run on t2 provides no results. I suspect this is because the keys are strings instead of integers (index values), but I'm not sure why that matters.
I'm looking for A) why table.concat doesn't accept string keys, and/or B) a workaround that would allow me to concatenate a variable number of table values in a handful of lines, without specifying the key names.
Because that's what table.concat is documented as doing.
Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ยทยทยท sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.
Non-array tables have no defined order so table.concat wouldn't be all that helpful then anyway.
You can write your own, inefficient, table concat function easily enough.
function pconcat(tab)
local ctab, n = {}, =1
for _, v in pairs(tab) do
ctab[n] = v
n = n + 1
end
return table.concat(ctab)
end
You could also use next manually to do the concat, etc. yourself if you wanted to construct the string yourself (though that's probably less efficient then the above version).

How to return very long integer in Lua

I am trying to return very long integer number but my result returns as
"7.6561197971049e+016".
How do I make it return 76561197971049296 ?
local id64 = 76561197960265728
Z = string.match("STEAM_0:0:5391784", 'STEAM_%d+:%d+:(%d+)')
Y = string.match("STEAM_0:0:5391784", 'STEAM_%d+:(%d+):%d+')
--For 64-bit systems
--Let X, Y and Z constants be defined by the SteamID: STEAM_X:Y:Z.
--Let V be SteamID64 identifier of the account type (0x0110000100000000 in hexadecimal format).
--Using the formula W=Z*2+V+Y
if Z == nil then
return "none"
else
return Z*2+id64+Y
end
I installed lbc arbitrary precision now with this code
return bc.add(bc.number(id64),bc.number(2)):tostring()
it returns 70000000000000002 but if I delete 3 digits from id64 it displays correctly.
How can I get correct result without deleting the digits?
You need to use strings for long numbers. Otherwise, the Lua lexer converts them to doubles and loses precision in this case. Here is code using my lbc:
local bc=require"bc"
local id64=bc.number"76561197960265728"
local Y,Z=string.match("STEAM_0:0:5391784",'STEAM_%d+:(%d+):(%d+)')
if Z == nil then
return "none"
else
return (Z*2+id64+Y):tostring()
end
check out this library for arbitrary precision arithmetics. this so post might be of interest to you as well.
Assuming your implementation of Lua supports that many significant digits in the number type, your return statement is returning that result.
You're probably seeing exponential notation when you convert the number to a string or printing it. You can use the string.format function to control the conversion:
assert( "76561197971049296" == string.format("%0.17g", 76561197971049296))
If number is an IEEE-754 double, then it doesn't work. You do have to know how your Lua is implemented and keep in mind the the technical limitations.
If you have luajit installed, you can do this:
local ffi = require("ffi")
steamid64 = tostring(ffi.new("uint64_t", 76561197960265728) + ffi.new("uint64_t", tonumber(accountid)))
steamid64 = string.sub(steamid64, 1, -4) -- to remove 'ULL at the end'
Hope it helps.

Resources