Reputation: 21
I do not want to use string.reverse()
instead I want to create my own way. But I am failing.
Where did I go wrong:
function wait(n)
local now = os.time()
while os.time() - now < n do end
end
sit = "1234 1234"
function revers(sit)
wait(1)
local table = { " nil "}
print(#sit, os.date("%M"))
while #table < #sit do
table.insert(table, #table+1, sit:find(".", #sit))
print(#table, #sit)
wait(1)
end
end
revers(sit)
Upvotes: 1
Views: 1141
Reputation: 9
This copies array a value "Wednesday" to array b in reverse order.
#include <stdio.h>
main()
{
char a[] = "Wednesday";
char b[12];
char *a_ptr, *b_ptr;
int lkm = 0; /* number of characters */
int i = 0;
while(a[i] != '\0')
{
i++;
lkm++;
}
lkm = lkm - 1;
a_ptr = a;
b_ptr = b;
a_ptr += lkm;
int j;
for(j = lkm; j >= 0; j--)
{
*b_ptr = *a_ptr;
a_ptr--;
b_ptr++;
}
fprintf(stdout, "Before: %s\n", a);
fprintf(stdout, "After: %s\n", b);
return(0);
}
Program output:
Before: Wednesday
After: yadsendeW
Upvotes: -1
Reputation: 1351
Sorry to say, but your code has some fundamental issues:
revers
does not return anythingrevers
only attempts to build a table, not a stringnil
, either as key or as valuesit:find(".",#sit)
uses the wrong, constant starting point for the findTry to understand the following code that should do the job:
function revers(s)
local r = ""
for i = 1,#s,1 do
r = s:sub(i,i) .. r
end
return r
end
Upvotes: 3
Reputation: 8207
You should just try to loop through each character in sit
and write it to a table
. Try using this instead of your while
loop
for c in str:gmatch"." do
table.insert(table,c)
-- or
table = table .. c -- the table shouldn't be initialized nil in this case
end
Upvotes: 0
Reputation: 6184
The issue is
local table = { " nil " }
You can't name a variable after a reserved word. If you change it to
local mytable = { " nil " }
Also change all subsequent uses like so:
function wait(n)
local now = os.time()
while os.time() - now < n do end
end
sit = "1234 1234"
function revers(sit)
wait(1)
local mytable = { " nil "}
print(#sit, os.date("%M"))
while #mytable < #sit do
mytable.insert(mytable, #mytable+1, sit:find(".", #sit))
print(#mytable, #sit)
wait(1)
end
end
revers(sit)
A simpler way to do this though is:
function revers(sit)
local mytable = { " nil "}
for i = 0, #sit+1 do
table.insert(mytable, string.sub(sit, #sit-i, #sit-i))
end
end
The table now contains an array of the string characters in reverse order.
Upvotes: 0