Trusted answers to developer questions
Trusted Answers to Developer Questions

RELATED TAGS

lua

What is the string.rep() method in Lua?

NDUKWE CHIDERA K.

Overview

The string.rep() method in Lua duplicates and concatenates a string indicated the number of times.

For example, string.rep(A,2) simply implies that the values of string variable A should be repeated twice. The value of A repeated will be returned by the method.

Technically, this function creates a storage location into which the value to be repeated is pushed till the number of times it is to be repeated is reached. When this happens, this storage location is returned or stored in a named variable is displayed with the repeated values.

Syntax

string.rep(repString,repCount)

Parameters

  • repString: This is the string value that will be repeated the indicated number of times.
  • repCount: This is a number that indicates the number of times to repeat the repString value.

Return value

The return value is of type string. This is the value of repString repeated as much as repCount times.

Code example

In the code snippet below, we’ll repeat the value of different variables using the repeat method.


--declare string variables to be repeated
repeat1 = "Educative"
repeat2 = "Edpresso shots"
repeat3 = "23449 "
repeat4 = 23449

--declare a table variable
repeat5 = {3, 2, 7, "repeat "}

--call the string.rep method
print(string.rep(repeat1,3))
print(string.rep(repeat2,2))
print(string.rep(repeat3,4))
print(string.rep(repeat4,2))
--print(string.rep(repeat5,2))
output = (string.rep(repeat5[4],2))
print(output)

Code explanation

  • Lines 3 to 9: We declare the variable of varying types.

  • Lines 12-14: We attempt to repeat the contents of some string variables, and the result is displayed successfully.

  • Line 15: We call the string.rep() method on a number value. It worked because numbers are convertible to string numbers.

  • Line 17: We select a single element from the table value: repeat5 and repeat it using the string.rep() method.

  • Line 18: We print the outcome of the operation from lines 0 to 17.

Note: If we uncomment line 16, the function displays an error message informing us that a table or chunk (that is a function block) cannot be passed as its argument. Therefore, the allowable types are strings and numbers (because numbers can be converted to strings and vice versa).

RELATED TAGS

lua
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time

Copyright ©2022 Educative, Inc. All rights reserved.

soc2