This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Liraal's profile picture

A little problem

Started by Liraal, 11 March 2012 - 07:50 PM
Liraal #1
Posted 11 March 2012 - 08:50 PM
This function refuses to work. Any ideas?

function delete(x,y)
local tmp1=""
local tmp2=""
local base=text[y]
for i=1, x-1, 1 do
tmp1=tmp1..string.sub(base,i,i)
end
for j=x+1, string.len(base), 1 do
tmp2=tmp2..string.sub(base,j,j)
end
text[y]=tmp1..tmp2
return true
end
'text' is an array of strings.
Espen #2
Posted 11 March 2012 - 09:03 PM
It looks like you're trying to remove a character from a string, right?
The string.sub() function allows you to select a range of characters by defining the start and end position of the string, i.e. you don't have to iterate through the string character by character:

function delete( x, y )
  local head = string.sub( text[ y ], 1, x - 1 )
  local tail = string.sub( text[ y ], x + 1 )
 
  text[ y ] = head..tail
  return true
end

EDIT: Tweaked the code a bit more.
Edited on 11 March 2012 - 08:05 PM
Liraal #3
Posted 11 March 2012 - 09:11 PM
Thanks, looks pretty obvious now :mellow:/>/>
Anyway, it seems that the error is with parring x and y to the function. It's going to be hard to find.
Espen #4
Posted 11 March 2012 - 09:19 PM
Also, if you'll allow me to make a suggestion: With a little tweak you can make this function work universally for any string, so that it's not limited to the text-table you defined:

function delete( sText, x )
  local head = string.sub( sText, 1, x - 1 )
  local tail = string.sub( sText, x + 1 )

  return head..tail
end

This way you'd call it like this:

text[2] = delete( text[2], 3 )

If you don't want to write as much everytime, then you can just create an additional small function, specially geared towards the text-table, that wraps the delete function:

function textDelete( index, charPos )
  text[ index ] = delete( text[ index ], charPos )
end

The nice thing about doing it this way is that you can just call textDelete() if you want to delete characters specifically from the text-table, but you can also call delete() on any other string if you need to anytime later.