Ascii、UTF-8、または UTF-16 のテキスト ファイルを読み取る汎用関数を作成しています。(エンコーディングは、関数が呼び出されるときに認識されます)。ファイル名には UTF8 文字が含まれている可能性があるため、標準の lua io 関数は解決策ではありません。Lua 実装 (5.3) または環境で利用可能なバイナリ モジュールを制御できません。
私の現在のコードは次のとおりです。
require "luacom"
local function readTextFile(sPath, bUnicode, iBits)
local fso = luacom.CreateObject("Scripting.FileSystemObject")
if not fso:FileExists(sPath) then return false, "" end --check the file exists
local so = luacom.CreateObject("ADODB.Stream")
--so.CharSet defaults to Unicode aka utf-16
--so.Type defaults to text
so.Mode = 1 --adModeRead
if not bUnicode then
so.CharSet = "ascii"
elseif iBits == 8 then
so.CharSet = "utf-8"
end
so:Open()
so:LoadFromFile(sPath)
local contents = so:ReadText()
so:Close()
return true, contents
end
--test Unicode(utf-16) files
local file = "D:\\OneDrive\\Desktop\\utf16.txt" --this exists
local booOK, factsetcontents = readTextFile(file, true, 16)
実行すると、次のエラーが表示されます: COM exception:(d:\my\lua\luacom-master\src\library\tluacom.cpp,382):Operation is not allowed in this context
19 行目 [local stream = so:LoadFromFile(sPath)]
私は ADO のドキュメントを熟読しましたが、明らかに私を見つめている何かが欠けています! 私がやろうとしていることは不可能ですか?
ETA : so.Mode = 1 という行をコメント アウトすると、これで機能します。これは素晴らしいことですが、その理由がわかりません。つまり、その間違いが何であれ、無意識のうちに同じ間違いを犯してしまう可能性があるということです!