1

These days I am working on a small example/project of myself. What I am doing is creating n set of random strings of variable lengths. Here is what I want to obtain:

  • Two names of length from 3 to 25 characters.
  • A message ranging from 40 to 300 characters.

In my C example, I create a struct and kept inserting into this table as list. In my LUA example, I want a nested table like this:

tTableName = {
  [1] = {
    "To" = "Name 1",
    "From" = "Name 2",
    "Message" = "The first message generated"
  }
  [2] = {
    "To" = "Name 3",
    "From" = "Name 4",
    "Message" = "The second message generated"
  }
}

So, basically my structure goes like this:

struct PM {
  char *sTo, *sFrom, *sMessage;
} PMs;

I want a similar structure/table in LUA so that I can use a table.insert method. I currently am doing it like this:

tTempTable = {
  "To" = "Name 1",
  "From" = "Name 2",
  "Message" = "The first message generated"
}
table.insert( tTableName, tTempTable )

but I am thinking it as a wastage of a lot of processing time. Currently I am only generating a sample of 30 such PMs; but later I shall be generating *1000*s of them. Please advice.

4

2 に答える 2

2

ボトルネックがどこにあるかを知る前に、コードを時期尚早に最適化するという罠に陥っていると思います...しかし、次のドキュメントには、表を含むlua全般に関する最適化情報がたくさん含まれています。これを書いた人は、Lua のヘッド アーキテクトの 1 人です。

http://www.lua.org/gems/sample.pdf

于 2012-05-12T13:38:40.887 に答える
1

まず第一に、これは本当に質問ではありません。これを行うためのより効率的な方法があるかどうかを尋ねていると思いますか?一般に、問題が発生しない限り、明確にするために記述し、小さなパフォーマンスの向上を気にする必要はありません。ただし、効率に関するいくつかの注意事項を含む、コードに関する注意事項を次に示します。

投稿されたテーブル コンストラクターが無効です。次の修正のいずれかが機能します。

tTempTable = {
  ["To"] = "Name 1",
  ["From"] = "Name 2",
  ["Message"] = "The first message generated"
}
tTempTable = {
  To = "Name 1",
  From = "Name 2",
  Message = "The first message generated"
}

配列を作成するときに数値インデックスを指定する必要はありません。これを置き換えることができます:

tTableName = {
  [1] = { To = "Name 1", From = "Name 2", Message = "The first message generated" },
  [2] = { To = "Name 3", From = "Name 4", Message = "The second message generated" },
}

これは、まったく同じことを意味しますが、より簡潔です。

tTableName = {
  { To = "Name 1", From = "Name 2", Message = "The first message generated" },
  { To = "Name 3", From = "Name 4", Message = "The second message generated" },
}

これはたまたまより効率的です。Lua は必要な配列サイズを事前に割り当てることができますが、前のコンストラクターでそれを行うほどスマートではありません。

これを一般的に記述するより良い方法については、アプリケーションについて詳しく知らずに言うのは難しいです。いくつかの PM コードをテストしようとしているだけなら、使用時に必要な文字列をオンザフライで生成してみませんか? なぜそれらをテーブルに事前に割り当てるのですか?

事前に割り当てる必要がある場合は、それらを構造化データとして保存する必要はありません。ToNames、FromNames、Messages の 3 つの配列を使用して、使用時にランダムに選択することができます。

local to      =  ToNames  [ math.random(1,#ToNames  ) ]
local from    =  FromNames[ math.random(1,#FromNames) ]
local message =  Messages [ math.random(1,#Messages ) ]
TestPM(to, from, message)
于 2012-05-12T20:40:28.287 に答える